I need to change the values of a PK/FK (add 10000) on 2 tables. How do I tell the two tables involved that they should not care about referential integrity during the update, but to care a开发者_运维技巧fter. I don't want to have to drop and recreate the relationships if I don’t have to.
You may want to disable all the constraints in the database by executing the following command:
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all";
Then switching them back on with:
EXEC sp_msforeachtable @command1="print '?'",
@command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all";
Source: Stack Overflow - Can foreign key constraints be temporarily disabled using TSQL?
Your FK should have a "ON UPDATE CASCADE" option.
ALTER TABLE child CHANGE myfkconst FOREIGN KEY id REFERENCES parent (id) ON UPDATE CASCADE;
(or something like that. not 100% sure about the syntax)
And then you can just do
UPDATE parent SET id = id + 10000 WHERE id = something
and the child table will be updated automatically.
This link describes how to temporarily disable a contraint. I have not tested it.
-- disable constraint
ALTER TABLE table_name NOCHECK CONSTRAINT constraint_name
-- enable constraint
ALTER TABLE table_name CHECK CONSTRAINT constraint_name
Sorry, you have to. No option.
精彩评论