Copy Data To Existing Rows Within Same Table in SQL Server

房东的猫 提交于 2019-12-24 15:27:21

问题


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!


回答1:


You can use table variables to store the IDs to be updated:

DECLARE @tbl TABLE(ID INT PRIMARY KEY);
INSERT INTO @tbl VALUES (2), (3), (5);

DECLARE @destID INT = 4

UPDATE widgets 
    SET price = (SELECT price FROM widgets WHERE ID = @destID)
WHERE
    ID IN(SELECT ID FROM @tbl)

Alternatively, you can store the source ID and destination ID in a single table variable. For this case, you need to store (2, 4), (3, 4) and (5, 4).

DECLARE @tbl TABLE(srcID INT, destID INT, PRIMARY KEY(srcID, destID));
INSERT INTO @tbl VALUES (2, 4), (3, 4), (5, 4);

UPDATE s
    SET s.Price = d.Price
FROM widgets s
INNER JOIN @tbl t ON t.srcID = s.ID
INNER JOIN widgets d
    ON d.ID = t.destID


来源:https://stackoverflow.com/questions/33949195/copy-data-to-existing-rows-within-same-table-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!