如何同时更改主键值和更新外键
我的表中有一条记录的主键错误。我想将其更改为正确的值,但该值已在许多其他表中使用。
有没有什么简单的方法可以同时更新主键和外键?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果外键设置为级联更改,则该值应自动更改。
If the foreign keys are set to cascade changes then the value should change automatically.
确保您的外键关系已指定 ON UPDATE CASCADE,并且外键将自动更新以匹配主键。
来自在线书籍:
http://msdn.microsoft.com/en -us/library/ms174123%28v=SQL.90%29.aspx
Make sure that your foreign key relationships have ON UPDATE CASCADE specified, and the foreign key will automatically update to match the primary key.
From Books Online:
http://msdn.microsoft.com/en-us/library/ms174123%28v=SQL.90%29.aspx
更新主键不会更新相关的外键,它只会删除其他表上的相关记录,因为Sql Server将更新视为删除和插入。这是Sql Server 2000,不确定更高版本。使用“级联更新上级联删除”,“删除和插入:又名更新”的级联效果,删除其他表上的相关记录。
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.
如果您想在主键更改时更新外键,我们可以在外键引用上使用“ON UPDATE CASCADE”命令。
这里,“Customer”表中的外键“salesman_id”引用“Salesman”表中的主键“salesman_id”。由于我们在外键引用中使用了“ON UPDATE CASCADE”,因此对“Salesman”表中的 salesman_id 所做的更改也将反映在客户表的“salesman_id”字段中。
因此,当引用表中的主键值发生更改时,我们使用“ON UPDATE CASCADE”自动更新相关表中的外键值
If You want to update the foreign key when the primary key is changed , we can use 'ON UPDATE CASCADE' command on Foreign Key References .
Here the Foreign key 'salesman_id' in 'Customer' table references Primary Key 'salesman_id' in 'Salesman' table. As We Used 'ON UPDATE CASCADE' in the foreign key references , the changes made for the salesman_id in the 'Salesman' table will also get reflected in the customer tables 'salesman_id' Field .
So, We Use 'ON UPDATE CASCADE' To Automatically Update the Foreign Key Values in the related table when the value of primary key is changed in the reference Table