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

后端 未结 8 2004
北海茫月
北海茫月 2020-12-17 14:59

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:

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 15:18

    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.

    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.

提交回复
热议问题