I head some time left, so here is the script. If you also need to disable and enable triggers, just let me know and we will expand the script.
SET NOCOUNT ON;
DECLARE @Statement varchar(1000);
/* Remove the statement below if you are really going to use this script. */
/* The statement below just helps you see what is going on with the constraints. */
SELECT TOP 5 [name], is_disabled, is_not_trusted FROM sys.foreign_keys ORDER BY [name], parent_object_id;
DECLARE cr_Disable_FKs CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
SELECT 'ALTER TABLE ' + SCHEMA_NAME(TAB.[schema_id]) + '.' + TAB.[name] + ' NOCHECK CONSTRAINT ' + FK.[name] + ';'
FROM sys.foreign_keys AS FK
INNER JOIN sys.tables AS TAB
ON TAB.[object_id] = FK.parent_object_id;
OPEN cr_Disable_FKs;
FETCH cr_Disable_FKs INTO @Statement;
PRINT 'Disable FKs';
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @Statement;
EXECUTE (@Statement);
FETCH cr_Disable_FKs INTO @Statement;
END;
PRINT ' ';
CLOSE cr_Disable_FKs;
DEALLOCATE cr_Disable_FKs;
/* Remove the statement below if you are really going to use this script. */
/* The statement below just helps you see what is going on with the constraints. */
SELECT TOP 5 [name], is_disabled, is_not_trusted FROM sys.foreign_keys ORDER BY [name], parent_object_id;
/* This is the place your delete statements should be inserted */
PRINT '<Insert your delete statements here>';
PRINT ' ';
DECLARE cr_Enable_FKs CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
SELECT 'ALTER TABLE ' + SCHEMA_NAME(TAB.[schema_id]) + '.' + TAB.[name] + ' CHECK CONSTRAINT ' + FK.[name] + ';'
FROM sys.foreign_keys AS FK
INNER JOIN sys.tables AS TAB
ON TAB.[object_id] = FK.parent_object_id;
OPEN cr_Enable_FKs;
FETCH cr_Enable_FKs INTO @Statement;
PRINT 'Enable FKs';
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @Statement;
EXECUTE (@Statement);
FETCH cr_Enable_FKs INTO @Statement;
END;
PRINT ' ';
CLOSE cr_Enable_FKs;
DEALLOCATE cr_Enable_FKs;
/* Remove the statement below if you are really going to use this script. */
/* The statement below just helps you see what is going on with the constraints. */
SELECT TOP 5 [name], is_disabled, is_not_trusted FROM sys.foreign_keys ORDER BY [name], parent_object_id;
DECLARE cr_Check_FKs CURSOR LOCAL FORWARD_ONLY STATIC READ_ONLY FOR
SELECT 'ALTER TABLE ' + SCHEMA_NAME(TAB.[schema_id]) + '.' + TAB.[name] + ' WITH CHECK CHECK CONSTRAINT ' + FK.[name] + ';'
FROM sys.foreign_keys AS FK
INNER JOIN sys.tables AS TAB
ON TAB.[object_id] = FK.parent_object_id;
OPEN cr_Check_FKs;
FETCH cr_Check_FKs INTO @Statement;
PRINT 'Make FKs trusted again';
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @Statement;
EXECUTE (@Statement);
FETCH cr_Check_FKs INTO @Statement;
END;
CLOSE cr_Check_FKs;
DEALLOCATE cr_Check_FKs;
/* Remove the statement below if you are really going to use this script. */
/* The statement below just helps you see what is going on with the constraints. */
SELECT TOP 5 [name], is_disabled, is_not_trusted FROM sys.foreign_keys ORDER BY [name], parent_object_id;
GO