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

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

    One script to rule them all: this combines truncate and delete commands with sp_MSforeachtable so that you can avoid dropping and recreating constraints - just specify the tables that need to be deleted rather than truncated and for my purposes I have included an extra schema filter for good measure (tested in 2008r2)

    declare @schema nvarchar(max) = 'and Schema_Id=Schema_id(''Value'')'
    declare @deletiontables nvarchar(max) = '(''TableA'',''TableB'')'
    declare @truncateclause nvarchar(max) = @schema + ' and o.Name not in ' +  + @deletiontables;
    declare @deleteclause nvarchar(max) = @schema + ' and o.Name in ' + @deletiontables;        
    
    exec sp_MSforeachtable 'alter table ? nocheck constraint all', @whereand=@schema
    exec sp_MSforeachtable 'truncate table ?', @whereand=@truncateclause
    exec sp_MSforeachtable 'delete from ?', @whereand=@deleteclause
    exec sp_MSforeachtable 'alter table ? with check check constraint all', @whereand=@schema
    

提交回复
热议问题