Swapping two rows in MS SQLServer retaining the original primary key and without manual update(在 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 中交换两行保留原始主键且无需手动更新
基础教程推荐
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 在多列上分布任意行 2021-01-01
- oracle区分大小写的原因? 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
