views:

558

answers:

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.

A: 

Not sure what you mean, "besides executing update command manually". How else do you propose changing data in the database? There's only a few commands to deal with data manipulation...

Joe
A: 

self join with an update is your only safe bet

SQLMenace
+1  A: 

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.
Thank you so much. Yours is I think is better than what I have currently to solve this problem. Your Query worked fine.
Shiva
I'm glad that I could help. If this is what you end up going with, please mark the answer as accepted.
Tom H.