Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to drop
and then re-create
WITH CHECK CHECK
is almost certainly required!
This point was raised in some of the answers and comments but I feel that it is important enough to call it out again.
Re-enabling a constraint using the following command (no WITH CHECK
) will have some serious drawbacks.
ALTER TABLE MyTable CHECK CONSTRAINT MyConstraint;
WITH CHECK | WITH NOCHECK
Specifies whether the data in the table is or is not validated against a newly added or re-enabled FOREIGN KEY or CHECK constraint. If not specified, WITH CHECK is assumed for new constraints, and WITH NOCHECK is assumed for re-enabled constraints.
If you do not want to verify new CHECK or FOREIGN KEY constraints against existing data, use WITH NOCHECK. We do not recommend doing this, except in rare cases. The new constraint will be evaluated in all later data updates. Any constraint violations that are suppressed by WITH NOCHECK when the constraint is added may cause future updates to fail if they update rows with data that does not comply with the constraint.
The query optimizer does not consider constraints that are defined WITH NOCHECK. Such constraints are ignored until they are re-enabled by using ALTER TABLE table WITH CHECK CHECK CONSTRAINT ALL.
Note: WITH NOCHECK is the default for re-enabling constraints. I have to wonder why...
The sys.foreign_keys system view provides some visibility into the issue. Note that it has both an is_disabled
and an is_not_trusted
column. is_disabled
indicates whether future data manipulation operations will be validated against the constraint. is_not_trusted
indicates whether all of the data currently in the table has been validated against the constraint.
ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint;
Are your constraints to be trusted? Find out...
SELECT * FROM sys.foreign_keys WHERE is_not_trusted = 1;