在MS SQLServer中交换两行,保留原始主键,无需手动更新 [英] Swapping two rows in MS SQLServer retaining the original primary key and without manual update

查看:188
本文介绍了在MS SQLServer中交换两行,保留原始主键,无需手动更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:我有像

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.

推荐答案

我没有测试这个,但我认为它会工作。我假设id是单列主键。如果不是这样,那么您需要稍微调整此代码来处理PK。

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)

这篇关于在MS SQLServer中交换两行,保留原始主键,无需手动更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆