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

后端 未结 16 1930
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: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
    

提交回复
热议问题