is it possible to swap primary key values between two datasets? If so, how would one do that?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Let’s for the sake of simplicity assume you have two records
both from table t (but they can come from different tables)
You could do
Note:
Updating primary keys has other side effects and maybe the preferred approach would be to leave the primary keys as they are and swap the values of all the other columns.
Caveat:
The reason why the
t.id = t2.id, t2.id = t.idworks is because in SQL the update happens on a transaction level. Thet.idis not variable and=is not assignment. You could interpret it as “set t.id to the value t2.id had before the effect of the query, set t2.id to the value t.id had before the effect of the query”. However, some databases might not do proper isolation, see this question for example (however, running above query, which is probably considered multi table update, behaved according to the standard in mysql).