在 MS SQLServer 中交换两行保留原始主键且无需手动更新

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

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

问题描述

我有以下问题:我有像

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.

推荐答案

我没有测试过这个,但我认为它会工作.我假设 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 中交换两行保留原始主键且无需手动更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 MS SQLServer 中交换两行保留原始主键且无需手动更新

基础教程推荐