且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQL Server 更新主键,同时也是两个表中的外键

更新时间:2022-12-11 11:08:15

您可以:

  1. 暂时禁用强制 FK 约束(请参阅此处此处)
  2. 更新您的 PK
  3. 更新您的 FK
  4. 启用反向执行 FK 约束

在一个事务中完成所有操作,并确保如果事务失败,您可以正确回滚它并仍然强制执行 FK 约束.

do it all within a transaction and make sure that if transaction fails, you roll it back properly and still enforce the FK constraints back.

但是……为什么要换PK?我希望这是一个很少执行的操作(旧数据导入或类似的操作).

But... why do you need to change a PK? I hope this is an action that is executed rarely (legacy data import or something like that).