SQL 如何同时更改主键的值和更新外键的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6388063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:02:20  来源:igfitidea点击:

How to change value of primary key and update foreign key in the same time

sqlsql-server-2005primary-key

提问by user278618

I have a record in table with wrong primary key. I want change it to correct value, but this value is used in many other tables.

我在表中有一条主键错误的记录。我想将其更改为正确的值,但该值已用于许多其他表中。

Is there any simple way to update primary key and foreign key at the same tim?

有没有什么简单的方法可以同时更新主键和外键?

回答by Ray

If the foreign keys are set to cascade changes then the value should change automatically.

如果外键设置为级联更改,则该值应自动更改。

回答by Michael Fredrickson

Make sure that your foreign key relationships have ON UPDATE CASCADE specified, and the foreign key will automatically update to match the primary key.

确保您的外键关系指定了 ON UPDATE CASCADE,外键将自动更新以匹配主键。

From Books Online: http://msdn.microsoft.com/en-us/library/ms174123%28v=SQL.90%29.aspx

来自在线书籍:http: //msdn.microsoft.com/en-us/library/ms174123%28v=SQL.90%29.aspx

ON UPDATE {CASCADE | NO ACTION | SET DEFAULT | SET NULL}

Specifies what action happens to a row in the table that is created when that row has a referential relationship, and the referenced row is updated in the parent table. The default is NO ACTION. See the "Remarks" section later in this topic for more information.

更新 {CASCADE | 没有行动 | 设置默认值 | 设置为空}

指定当该行具有引用关系并且被引用行在父表中更新时创建的表中的行会发生什么操作。默认值为无操作。有关详细信息,请参阅本主题后面的“备注”部分。

回答by alex

Updating a primary key does not update related foreign keys, it only deletes the related records on other tables as Sql Server treats update as delete and insert. This is Sql Server 2000, not sure later versions. Using "on cascading update on cascading delete", the cascading effects of the "delete and insert:aka update", deletes the related records on other tables.

更新主键不会更新相关的外键,它只会删除其他表上的相关记录,因为 Sql Server 将更新视为删除和插入。这是Sql Server 2000,不确定更高版本。使用“on cascading update on cascading delete”,“delete and insert:aka update”的级联效果,删除其他表上的相关记录。