Skip to content

Instantly share code, notes, and snippets.

@adautoneto
Created November 29, 2012 04:45
Show Gist options
  • Save adautoneto/4166853 to your computer and use it in GitHub Desktop.
Save adautoneto/4166853 to your computer and use it in GitHub Desktop.
Enabling and Disabling Foreign Keys on SQL Server
--Disable foreign keys on all tables
DECLARE @table_name SYSNAME;
DECLARE @cmd NVARCHAR(MAX);
DECLARE table_cursor CURSOR FOR SELECT name FROM sys.tables;
OPEN table_cursor;
FETCH NEXT FROM table_cursor INTO @table_name;
WHILE @@FETCH_STATUS = 0 BEGIN
SELECT @cmd = 'ALTER TABLE [' + @table_name + '] NOCHECK CONSTRAINT ALL';
EXEC (@cmd);
FETCH NEXT FROM table_cursor INTO @table_name;
END
CLOSE table_cursor;
DEALLOCATE table_cursor;
GO
--Enable foreign keys on all tables
DECLARE @table_name SYSNAME;
DECLARE @cmd NVARCHAR(MAX);
DECLARE table_cursor CURSOR FOR SELECT name FROM sys.tables;
OPEN table_cursor;
FETCH NEXT FROM table_cursor INTO @table_name;
WHILE @@FETCH_STATUS = 0 BEGIN
SELECT @cmd = 'ALTER TABLE [' + @table_name + '] CHECK CONSTRAINT ALL';
EXEC (@cmd);
FETCH NEXT FROM table_cursor INTO @table_name;
END
CLOSE table_cursor;
DEALLOCATE table_cursor;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment