Created
November 29, 2012 04:45
-
-
Save adautoneto/4166853 to your computer and use it in GitHub Desktop.
Enabling and Disabling Foreign Keys on SQL Server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--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