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:
If you only need to swap a couple of rows, then yeah, you can brute force it with tailor-made case statements and join statements like in the other answers. But if you need to operate on many rows, that's going to be a pain.
WITH map AS (
SELECT *
FROM (VALUES
(1, 2), -- Here's an example of swapping two rows:
(2, 1), -- 1 <- 2, 2 <- 1
(3, 4), -- Here's an example of rotating three rows:
(4, 5), -- 3 <- 4, 4 <- 5, 5 <- 3
(5, 3),
(6, 7) -- Here's an example of just copying one row to another: 3 <- 5
) AS a (destID, srcID)
)
UPDATE destination
SET
ColumnA = source.ColumnA,
ColumnB = source.ColumnB,
ColumnC = source.ColumnC
FROM
SomeTable AS destination
JOIN map ON map.destID = destination.ID
JOIN SomeTable AS source ON source.ID = map.srcID
Notes