SQL Remove All Constraints Azure Friendly SQL Remove All Constraints Azure Friendly sql sql

SQL Remove All Constraints Azure Friendly


While this link is for Amazon RDS, it does provide specific code to disable constraints without sp_MSForEachTable

Importing and Exporting SQL Server Data

-- Manually specify database name - a safeguard in case you paste this into the wrong SSMS window.USE [staging]-- Change this line if you want to enable (1) or disable constraints:DECLARE @enable_constraints bit = 0--Don't change anything below this line.DECLARE @schema_name SYSNAMEDECLARE @table_name  SYSNAMEDECLARE table_cursor CURSOR FORSELECT    schemas.name,    tables.nameFROM    sys.tables    INNER JOIN sys.schemas ON tables.schema_id = schemas.schema_idOPEN table_cursorFETCH NEXT FROM table_cursor INTO @schema_name, @table_nameDECLARE @cmd varchar(200) WHILE @@FETCH_STATUS = 0BEGIN    SET @cmd = 'ALTER TABLE ' + QUOTENAME(@schema_name) + '.' + QUOTENAME(@table_name) + ' '    SET @cmd = @cmd + (CASE WHEN @enable_constraints = 1 THEN 'CHECK' ELSE 'NOCHECK' END) + ' CONSTRAINT ALL'    PRINT @cmd    EXEC( @cmd )    FETCH NEXT FROM table_cursor INTO @schema_name, @table_nameENDCLOSE table_cursorDEALLOCATE table_cursor


Extended the script to deal with tables in different schemas, also corrected the above script that is not disabling checks:

    -- DISABLE ALL CONSTRAINTS DECLARE @table_name SYSNAME;DECLARE @schema_name SYSNAME;DECLARE @cmd NVARCHAR(MAX);DECLARE table_cursor CURSOR FOR    SELECT s.name, t.name     FROM sys.tables t    join sys.schemas s on t.schema_id = s.schema_idOPEN table_cursor;FETCH NEXT FROM table_cursor INTO @schema_name, @table_name;WHILE @@FETCH_STATUS = 0 BEGIN  SELECT @cmd = 'ALTER TABLE '+QUOTENAME(@schema_name)+'.'+QUOTENAME(@table_name)+' NOCHECK CONSTRAINT ALL';  EXEC (@cmd);  FETCH NEXT FROM table_cursor INTO  @schema_name, @table_name;ENDCLOSE table_cursor;DEALLOCATE table_cursor;-- enable all constraintsDECLARE table_cursor CURSOR FOR    SELECT s.name, t.name     FROM sys.tables t    join sys.schemas s on t.schema_id = s.schema_idOPEN table_cursor;FETCH NEXT FROM table_cursor INTO @schema_name, @table_name;WHILE @@FETCH_STATUS = 0 BEGIN  SELECT @cmd = 'ALTER TABLE '+QUOTENAME(@schema_name)+'.'+QUOTENAME(@table_name)+' CHECK CONSTRAINT ALL';  EXEC (@cmd);  FETCH NEXT FROM table_cursor INTO  @schema_name, @table_name;ENDCLOSE table_cursor;DEALLOCATE table_cursor;