In SQL, adding a set of values corresponding on a join
Let's say that I have Table_A contain:
ID OldValue
3 16
1 5
and Table_B contains
ID Value OldValue
1 2 NULL
2 4 NULL
3 8 NULL
and that I want to insert OldValues from Table_A into Table_B where the IDs 开发者_如何学运维equal resulting in :
updated Table_B
ID Value OldValue
1 2 5
2 4 NULL
3 8 16
Is there a set based way of doing this without using a cursor? In real life this will be going on very large tables and cursors, as we all know are slow. Perhaps some sort of Merge?
I'm on SQL Server 2008
Update Table_B
Set OldValue = A.OldValue
From Table_A As A
Join Table_B As B
On B.ID = A.ID
You want an "update from"
UPDATE B
SET B.OldValue = A.OldValue
FROM Table_B B
INNER JOIN Table_A ON B.ID = A.ID
Generally I write this as a select, then once i get the result I convert it over to the update.
Simple:
update x set OldValue = a.OldValue
from Table_B x
join Table_A a on x.ID = a.ID
Use a join:
UPDATE TABLE_B
SET OLDAVLUE=A.OLDVALUE
FROM TABLE_B B
LEFT JOIN TABLE_A A ON B.ID=A.ID
Perhaps some sort of Merge?
Indeed. The following is Standard SQL that is supported on SQL Server 2008:
MERGE INTO Table_B
USING Table_A
ON Table_B.ID = Table_A.ID
WHEN MATCHED THEN
UPDATE
SET OldValue = Table_A.OldValue;
精彩评论