1

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 after. I don't want to have to drop and recreate the relationships if I don’t have to.

4 Answers 4

4

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Does this also allow the IDENTITY column value to be changed?
That might be a bit more complicated. You can check this regarding identities: mssqltips.com/tip.asp?tip=1397
2

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.

Comments

2

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 CHECK CONSTRAINT constraint_name

2 Comments

You need to be aware that with this method, when you turn the constraints back on, the DB will do a data integrity check. Your data may fail if there is something wrong, and fixing it can be problematic. This is also explained here: stackoverflow.com/questions/159038/….
Yes, that's true, but this seems to be a simple case where the OP just needs to update each value by 10000, so this shouldn't be a problem. It seems the only answer that wouldn't have this problem would be changing the foreign key to be 'ON UPDATE CASCADE', which would change the foreign key rather than just disable it (which may be alright).
0

Sorry, you have to. No option.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.