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

后端 未结 16 1933
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;
    
    0 讨论(0)
  • 2020-11-22 05:37

    You can temporarily disable constraints on your tables, do work, then rebuild them.

    Here is an easy way to do it...

    Disable all indexes, including the primary keys, which will disable all foreign keys, then re-enable just the primary keys so you can work with them...

    DECLARE @sql AS NVARCHAR(max)=''
    select @sql = @sql +
        'ALTER INDEX ALL ON [' + t.[name] + '] DISABLE;'+CHAR(13)
    from  
        sys.tables t
    where type='u'
    
    select @sql = @sql +
        'ALTER INDEX ' + i.[name] + ' ON [' + t.[name] + '] REBUILD;'+CHAR(13)
    from  
        sys.key_constraints i
    join
        sys.tables t on i.parent_object_id=t.object_id
    where
        i.type='PK'
    
    
    exec dbo.sp_executesql @sql;
    go
    

    [Do something, like loading data]

    Then re-enable and rebuild the indexes...

    DECLARE @sql AS NVARCHAR(max)=''
    select @sql = @sql +
        'ALTER INDEX ALL ON [' + t.[name] + '] REBUILD;'+CHAR(13)
    from  
        sys.tables t
    where type='u'
    
    exec dbo.sp_executesql @sql;
    go
    
    0 讨论(0)
  • 2020-11-22 05:40

    Answer marked '905' looks good but does not work.

    Following worked for me. Any Primary Key, Unique Key, or Default constraints CAN NOT be disabled. In fact, if 'sp_helpconstraint '' shows 'n/a' in status_enabled - Means it can NOT be enabled/disabled.

    -- To generate script to DISABLE

    select 'ALTER TABLE ' + object_name(id) + ' NOCHECK CONSTRAINT [' + object_name(constid) + ']'
    from sys.sysconstraints 
    where status & 0x4813 = 0x813 order by object_name(id)
    

    -- To generate script to ENABLE

    select 'ALTER TABLE ' + object_name(id) + ' CHECK CONSTRAINT [' + object_name(constid) + ']'
    from sys.sysconstraints 
    where status & 0x4813 = 0x813 order by object_name(id)
    
    0 讨论(0)
  • 2020-11-22 05:40

    You should actually be able to disable foreign key constraints the same way you temporarily disable other constraints:

    Alter table MyTable nocheck constraint FK_ForeignKeyConstraintName
    

    Just make sure you're disabling the constraint on the first table listed in the constraint name. For example, if my foreign key constraint was FK_LocationsEmployeesLocationIdEmployeeId, I would want to use the following:

    Alter table Locations nocheck constraint FK_LocationsEmployeesLocationIdEmployeeId
    

    even though violating this constraint will produce an error that doesn't necessarily state that table as the source of the conflict.

    0 讨论(0)
  • 2020-11-22 05:41
    SET NOCOUNT ON
    
    DECLARE @table TABLE(
       RowId INT PRIMARY KEY IDENTITY(1, 1),
       ForeignKeyConstraintName NVARCHAR(200),
       ForeignKeyConstraintTableSchema NVARCHAR(200),
       ForeignKeyConstraintTableName NVARCHAR(200),
       ForeignKeyConstraintColumnName NVARCHAR(200),
       PrimaryKeyConstraintName NVARCHAR(200),
       PrimaryKeyConstraintTableSchema NVARCHAR(200),
       PrimaryKeyConstraintTableName NVARCHAR(200),
       PrimaryKeyConstraintColumnName NVARCHAR(200),
       UpdateRule NVARCHAR(100),
       DeleteRule NVARCHAR(100)   
    )
    
    INSERT INTO @table(ForeignKeyConstraintName, ForeignKeyConstraintTableSchema, ForeignKeyConstraintTableName, ForeignKeyConstraintColumnName)
    SELECT 
       U.CONSTRAINT_NAME, 
       U.TABLE_SCHEMA, 
       U.TABLE_NAME, 
       U.COLUMN_NAME
    FROM 
       INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
          INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
             ON U.CONSTRAINT_NAME = C.CONSTRAINT_NAME
    WHERE
       C.CONSTRAINT_TYPE = 'FOREIGN KEY'
    
    UPDATE @table SET
       T.PrimaryKeyConstraintName = R.UNIQUE_CONSTRAINT_NAME,
       T.UpdateRule = R.UPDATE_RULE,
       T.DeleteRule = R.DELETE_RULE
    FROM 
       @table T
          INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS R
             ON T.ForeignKeyConstraintName = R.CONSTRAINT_NAME
    
    UPDATE @table SET
       PrimaryKeyConstraintTableSchema  = TABLE_SCHEMA,
       PrimaryKeyConstraintTableName  = TABLE_NAME
    FROM @table T
       INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS C
          ON T.PrimaryKeyConstraintName = C.CONSTRAINT_NAME
    
    UPDATE @table SET
       PrimaryKeyConstraintColumnName = COLUMN_NAME
    FROM @table T
       INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE U
          ON T.PrimaryKeyConstraintName = U.CONSTRAINT_NAME
    
    --SELECT * FROM @table
    
    SELECT '
    BEGIN TRANSACTION
    BEGIN TRY'
    
    --DROP CONSTRAINT:
    SELECT
       '
     ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] 
     DROP CONSTRAINT ' + ForeignKeyConstraintName + '
       '
    FROM
       @table
    
    SELECT '
    END TRY
    
    BEGIN CATCH
       ROLLBACK TRANSACTION
       RAISERROR(''Operation failed.'', 16, 1)
    END CATCH
    
    IF(@@TRANCOUNT != 0)
    BEGIN
       COMMIT TRANSACTION
       RAISERROR(''Operation completed successfully.'', 10, 1)
    END
    '
    
    --ADD CONSTRAINT:
    SELECT '
    BEGIN TRANSACTION
    BEGIN TRY'
    
    SELECT
       '
       ALTER TABLE [' + ForeignKeyConstraintTableSchema + '].[' + ForeignKeyConstraintTableName + '] 
       ADD CONSTRAINT ' + ForeignKeyConstraintName + ' FOREIGN KEY(' + ForeignKeyConstraintColumnName + ') REFERENCES [' + PrimaryKeyConstraintTableSchema + '].[' + PrimaryKeyConstraintTableName + '](' + PrimaryKeyConstraintColumnName + ') ON UPDATE ' + UpdateRule + ' ON DELETE ' + DeleteRule + '
       '
    FROM
       @table
    
    SELECT '
    END TRY
    
    BEGIN CATCH
       ROLLBACK TRANSACTION
       RAISERROR(''Operation failed.'', 16, 1)
    END CATCH
    
    IF(@@TRANCOUNT != 0)
    BEGIN
       COMMIT TRANSACTION
       RAISERROR(''Operation completed successfully.'', 10, 1)
    END'
    
    GO
    
    0 讨论(0)
  • 2020-11-22 05:41

    Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, set Enforce foreign key constraint to 'Yes' (to enable foreign key constraints) or 'No' (to disable it).

    0 讨论(0)
提交回复
热议问题