Click here to Skip to main content
15,893,161 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have one table which is giving count of items to be updated in another table both having one column in common
for eg

#table1

Type
Purpose
Itemstoupdate

#table2
Name
Type
Purpose
Flag

I need to update flag to 1 in #table2
for those no of records which is equal to Itemstoupdate from table1 where type and purpose match

logic is something like the below one ..but the syntax i dont know. Please help me

What I have tried:

update top (Itemstoupdate)#table2
set Flag=1
from #table1 
where #table1.type=#table2.type and #table1.Purpose=#table2.purpose
Posted
Updated 16-Oct-18 2:47am

1 solution

Unfortunately your logic won't work - where you have Itemstoupdate you need a constant value. You can achieve it using a Common Table Expression (CTE)

e.g.
SQL
;with CTE AS
(
	SELECT ROW_NUMBER() OVER (ORDER BY NAME) AS RN,
	name, type, purpose, flag
	FROM #table2
)
Update A SET FLAG = 1
from CTE A
INNER JOIN #table1 B on  A.type = B.type and A.purpose = B.purpose
WHERE A.RN <= B.itemstoupdate
The key point here is the ORDER BY clause on the ROW_NUMBER function - TOP doesn't have much context without ORDER BY
 
Share this answer
 
Comments
Member 10112611 16-Oct-18 8:51am    
Thank you so much for the quick response
It worked for me.
CHill60 16-Oct-18 8:53am    
My pleasure!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900