Update duplicate records from another table

时间:2015-06-30 13:45:56

标签: sql sql-server sql-server-2008 sql-server-2012

I have 2 table structure as follows,

TableA

enter image description here

TableB

enter image description here

I try to update TableB with the following query,

update tableB set ID = b.ID from tableB a inner join tableA b on a.prod = b.prod

enter image description here

Prod a in TableB is getting updated with only ID as 1, although Prod a also has IDs as 2 and 3 in TableA.

How could we modify the update query to get all the IDs in TableB?

Expected Output:

enter image description here

1 个答案:

答案 0 :(得分:2)

Try using MERGE concept,

MERGE TableB AS T
USING TableA AS S
ON (T.ID = S.ID and T.Prod = S.Prod) 
WHEN NOT MATCHED BY TARGET 
    THEN INSERT(ID, Prod) VALUES(S.ID, S.Prod)
WHEN MATCHED 
    THEN UPDATE SET T.ID = S.ID, T.Prod = S.Prod

GO 

You should try this,

Update TableB set ID = A.ID from TableA A
Inner Join TableB B on B.Prod = A.Prod And B.ID = 0