更改主键值
我有10张桌子。每个表都被其他5个表的外键引用。
我需要更改这 10 个表的主键值。有什么方法可以更改它,以便它自动更改所有外键?
我正在使用 sql server 2008 并拥有管理工作室。
I have 10 tables. Each table referenced by foreign keys of other 5 tables.
I need to change the primary key value of those 10 tables. Is there any way to change it so that it will change automatically all the foreign keys?
I am using sql server 2008 and have the management studio.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
以下是如何使用
ON UPDATE CASCADE
外键选项执行此操作的示例。您感兴趣的部分是两个 ALTER TABLE 语句。如果您使用
IDENTITY
列作为主键,那么这会变得更加困难,因为您无法更新IDENTITY
列。Here is a sample how you can do it using the
ON UPDATE CASCADE
foreign key option. The part you'll be interested in are the twoALTER TABLE
statements.If you are using
IDENTITY
columns for your primary keys then this becomes more difficult as you can't update anIDENTITY
column.您需要为这些外键设置 ON UPDATE CASCADE:
然后您只需更新 FK,并且引用字段也将作为事务的一部分进行更新:
请注意,要更改约束,需要删除它们。
You need to set ON UPDATE CASCADE for those foreign keys:
Then you simply update the FKs and referring fields will also be updated as part of the transaction:
Note that to alter constraints they need to be dropped.
我自己从来没有这样做过,听起来这可能是一个坏主意。也就是说,我确实发现这篇文章介绍了执行此操作的两种方法:
http://support.microsoft。 com/kb/142480
一个使用存储过程和其他触发器。两者似乎都有点痛苦。
I have never done this myself, and it sounds like it might be a bad idea. That said, I did find this article which goes over two methods for doing this:
http://support.microsoft.com/kb/142480
One uses stored procs and the other triggers. Both seem like a bit of a pain.
IDENTITY 列的一个显着缺点是它无法直接更新。
解决方法是不在目标表中使用 IDENTITY,而是将其放在额外的表中。首先插入包含 IDENTITY 列的表,然后将生成的 IDENTITY 值插入到目标表中。
SQL Server 2012引入了与表无关的序列,这是对同一问题的更好的解决方案。序列不需要额外的表。
It's a significant disadvantage of an IDENTITY column that it can't be directly updated.
A workaround is not to use IDENTITY in the target table but put it in an extra table instead. Insert to the table with the IDENTITY column first, then insert the generated IDENTITY value to your target table.
SQL Server 2012 introduces table-independent Sequences, which are a better solution to the same problem. A sequence doesn't require the extra table.
我知道这并不是您问题的真正答案,但我来到这里是在寻找如何简单地设置(写入、插入、更新或其他)PK(主键)列。
因此,您必须禁用 PK 约束,插入您的值,然后再启用它,更新将不起作用。
I know this is not really the answer to your question but I came here while looking for how to simply set (write, insert, update or else) a PK (primary key) column.
So you have to disable the PK constraint, insert your value, and enable it afterward, updates will not work.