I want to swap the values from two rows in a table. I have the rows IDs of the two rows. Is there any query to do that? Here is an example. Before the query I have this:
row1 : 1,2,3 row2 : 5,6,7
After the swap I want this:
row1 : 5,6,7 row2 : 1,2,3
Advertisement
Answer
If you want to swap values from one row to the other for two known IDs try something like this:
x
--need to store the original values
SELECT
*,CASE WHEN id=123 then 987 ELSE 123 END AS JoinId
INTO #Temp
FROM YourTable
WHERE ID in (123,987)
--swap values
UPDATE y
SET col1=t.col1
,col2=t.col2
FROM YourTable y
INNER JOIN #Temp t ON y.id =t.JoinId
WHERE ID in (123,987)