Swap values for two rows in the same table in SQL Server

UPDATE t1
SET
t1.col1 = t2.col1
,t1.col2 = t2.col2
,t1.col3 = t2.col3
,t1.col4 = t2.col4
--and so forth...
FROM YourTable AS t1
INNER JOIN YourTable AS t2
    ON      (t1.ID = '1'
            AND t2.ID = '2')
        OR
            (t1.ID = '2'
            AND t2.ID = '1')

You don't necessarily need to use the ID column of your table, I believe you could search by any column, with the proper joining logic. Joining the table to itself is the trick.


If you want to swap values from one row to the other for two known IDs try something like this:

--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)

Simple update works:

UPDATE myTable
SET 
col1 = CASE WHEN col1 = 1 THEN 5 ELSE 1 END,
col2 = CASE WHEN col2 = 2 THEN 6 ELSE 2 END,
col3 = CASE WHEN col3 = 3 THEN 7 ELSE 3 END 

Result: row values are swapped.


If you just need to swap a couple of rows, then you can use tailor-made case statements and joins like in the other answers. If you need to operate on many rows, that's going to be a pain though. In that case, I suggest using a mapping table.

A Simple, Scalable Solution

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

  • You can do two-row swaps, many-row swaps, and copies. It's flexible.
  • Specify as many destination/source row pairs as needed. Only destination rows will be updated.
  • Specify the columns you want to be copied over. Only those columns will be updated.
  • There's no temporary table to clean up.
  • It's easy to reuse since the row IDs are listed in a single, obvious place.

Tags:

Sql

Sql Server