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

后端 未结 8 1969
北海茫月
北海茫月 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:20
    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.

    0 讨论(0)
  • 2020-12-17 15:22

    You need to select all records by "WHERE" condition, Then "SET" update by "CASE" condition.

    UPDATE tbl_Temp SET 
    fk_userType = CASE fk_userType WHEN 1 THEN 2 WHEN 2 THEN 1 END,
    fk_userRole = CASE fk_userRole WHEN 1 THEN 2 WHEN 2 THEN 1 END
    WHERE (fk_userType = 1 AND fk_userRole = 1) OR (fk_userType = 2 AND fk_userRole = 2);
    
    0 讨论(0)
提交回复
热议问题