How can foreign key constraints be temporarily disabled using T-SQL?

后端 未结 16 1909
Happy的楠姐
Happy的楠姐 2020-11-22 04:57

Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to drop and then re-create

16条回答
  •  渐次进展
    2020-11-22 05:35

    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...

    1. No existing data in the table will be evaluated during the execution of this command - successful completion is no guarantee that the data in the table is valid according to the constraint.
    2. During the next update of the invalid records, the constraint will be evaluated and will fail - resulting in errors that may be unrelated to the actual update that is made.
    3. Application logic that relies on the constraint to ensure that data is valid may fail.
    4. The query optimizer will not make use of any constraint that is enabled in this way.

    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;
    

提交回复
热议问题