3

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.

Juan Mellado
  • 14,973
  • 5
  • 47
  • 54
Shiva
  • 1,379
  • 1
  • 15
  • 32

2 Answers2

6

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)
Tom H
  • 46,766
  • 14
  • 87
  • 128
  • Thank you so much. Yours is I think is better than what I have currently to solve this problem. Your Query worked fine. – Shiva Jan 27 '09 at 20:09
-1

self join with an update is your only safe bet

SQLMenace
  • 132,095
  • 25
  • 206
  • 225