In SQL Server 2008, I want to update some of the rows with data from another row. For example, given the sample data below:
ID | NAME | PRICE
---------------------------------------
1 | Yellow Widget | 2.99
2 | Red Widget | 4.99
3 | Green Widget | 4.99
4 | Blue Widget | 6.99
5 | Purple Widget | 1.99
6 | Orange Widget | 5.99
I want to update rows with ID 2, 3, and 5 to have the price of row 4.
I found a nice solution to update a single row at Update the same table in SQL Server that basically looks like:
DECLARE @src int = 4
,@dst int = 2 -- but what about 3 and 5 ?
UPDATE DST
SET DST.price = SRC.price
FROM widgets DST
JOIN widgets SRC ON SRC.ID = @src AND DST.ID = @dst;
But since I'm need to update multiple rows I'm not sure how the JOIN
should look like. SRC.ID = @src AND DST.ID IN (2, 3, 5)
? (not sure if that's even valid SQL?)
Also, if anyone can explain how the solution above does not update all the rows in the table since there is no WHERE
clause, that would be great!
Any thoughts? TIA!