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.
我想交换它们保留所有旧的主键和约束。当然,我可以通过更新行轻松地解决这个问题。我想知道是否有人对这类问题有很好的解决方案,而不只是手动执行update命令。我真的非常感谢你的建议和建议。
2 个解决方案
#1
6
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.
我还没有测试过这个,但是我想它会有用的。我假设id是一个单列主键。如果不是这样,那么您需要稍微调整这段代码来处理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)
#2
-1
self join with an update is your only safe bet
自我加入更新是你唯一安全的选择
#1
6
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.
我还没有测试过这个,但是我想它会有用的。我假设id是一个单列主键。如果不是这样,那么您需要稍微调整这段代码来处理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)
#2
-1
self join with an update is your only safe bet
自我加入更新是你唯一安全的选择