在 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 中交换两行保留原始主键且无需手动更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)