Changing a record in a table (sql server) that has foreign keys?

假如想象 提交于 2019-12-11 06:38:10

问题


Does anyone know if there is a quicker way of editing a record that has foreign keys in a table (in sql server).. i will explain.. i have approx 5 tables that have there own ID but are linked together using a foreign key...

Hence i needed to change the foreign key (the contract number in my case), but i had to copy each record to a new record and edit it that way...

As if i try to edit the contract number it gives me the standard error of being associated and violates a foreign key etc

Surly there must be a better way?

ANy ideas?


回答1:


are you talking about changing the PK and then updating all the Fks? In that case enable cascade updates and this will be done automagically same with deletes, you enable cascade deletes

ON DELETE CASCADE

Specifies that if an attempt is made to delete a row with a key referenced by foreign keys in existing rows in other tables, all rows containing those foreign keys are also deleted. If cascading referential actions have also been defined on the target tables, the specified cascading actions are also taken for the rows deleted from those tables.

ON UPDATE CASCADE

Specifies that if an attempt is made to update a key value in a row, where the key value is referenced by foreign keys in existing rows in other tables, all of the foreign key values are also updated to the new value specified for the key. If cascading referential actions




回答2:


I'm not an SQL expert, but can't you set something like ON UPDATE CASCADE to automatically update the foreign key when the primary key is changed?




回答3:


Or try disabling the integrity constraint, do your changes and attempt to re-enable the constraint. Basically, if you didn't do it right you will get an error then (can't enable a constraint that would be violated).



来源:https://stackoverflow.com/questions/799100/changing-a-record-in-a-table-sql-server-that-has-foreign-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!