Question

I have the following problem : I have rows like

ID   CODE     NAME            .........
1    h1100h1  Cool example1   .........
2    h654441  Another cool1   .........

I would like to swap them retaining all old primary keys and constraints. Of course, I can easily solve this manually by updating the rows. I am kind of wondering whether anybody has any excellent solution for this kind of problem instead of just executing update command manually. I really really appreciate any suggestions or recommendations.

Was it helpful?

Solution

I haven't tested this, but I think it will work. I'm assuming that id is a single-column Primary Key. If that's not the case then you will need to adjust this code slightly to handle the 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 NULL
          END
WHERE
     T1.id IN (@id_1, @id_2)

OTHER TIPS

self join with an update is your only safe bet

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top