sql - Swapping two rows in MS SQLServer retaining the original primary key and without manual update -
I have the following problem: I have rows
ID code name ... ...... 1 H 1100 H1 Cool Example 1 ......... 2 H 654441 Another Cool 1 .........
I want to keep them all the old primary keys and obstacles, of course, I can easily solve myself manually by updating this line. I am wondering if anyone has any outstanding solution to this type of problem, instead of just manually updating the update command I really appreciate any tips or suggestions.
I have not tested this, but I think this work. I'm assuming that ID is a single-column primary key. If it does not, then you will need to adjust this code slightly to handle PK.
update T1 SET column_1 = T2.column_1, column_2 = T2.column_2, ... from dbo My_Table T1 INNER JOIN dbo.My_Table T2 ON T2.id = Case when T1.id = @ Id_1 THEN @ id_2 WHEN T1.id = @ id_2 THEN @ id_1 ELSE tap end where T1.id IN (@ id_1, @ id_2)
Comments
Post a Comment