Sometimes you have to "empty" the database, meaning you have to keep everything except data.
One way is to script "everything", drop DB and create it again.
Another way is to delete data table by table, taking care of FK constraints, or to drop all FKs, then to remove data and at the end to restore FKs.
Here are 2 scripts for creating SQL code to:
1. a) Drop all existing FKs
b) Truncate tables
c) Create all FKs
2. Delete data from all tables in proper order (kill children first parents later method
)
Script 1. TRUNCATE with drop/create FKs
- SET NOCOUNT ON
- GO
- SELECT 'USE [' + db_name() +']';
- SELECT 'ALTER TABLE ' +
- '[' + s.name + '].[' + t.name + ']' +
- ' DROP CONSTRAINT [' + f.name +']'
- FROM sys.foreign_keys f
- INNER JOIN sys.TABLES t ON f.parent_object_id=t.object_id
- INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
- WHERE t.is_ms_shipped=0;
- SELECT 'TRUNCATE TABLE ' + '[' + s.name + '].[' + t.name + ']'
- FROM sys.TABLES t
- INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
- WHERE t.is_ms_shipped=0;
- SELECT 'ALTER TABLE ' +
- '[' + s.name + '].[' + t.name + ']' +
- ' ADD CONSTRAINT [' + f.name + ']' +
- ' FOREIGN KEY (' +
- Stuff( (SELECT ', ['+col_name(fk.parent_object_id, fk.parent_column_id) +']'
- FROM sys.foreign_key_columns fk
- WHERE constraint_object_id = f.object_id
- ORDER BY constraint_column_id
- FOR XML Path('')
- ), 1,2,'') + ')' +
- ' REFERENCES [' +
- object_schema_name(f.referenced_object_id)+'].['+object_name(f.referenced_object_id) + '] (' +
- Stuff((SELECT ', ['+col_name(fc.referenced_object_id, fc.referenced_column_id)+']'
- FROM sys.foreign_key_columns fc
- WHERE constraint_object_id = f.object_id
- ORDER BY constraint_column_id
- FOR XML Path('')),
- 1,2,'') +
- ')' +
- ' ON DELETE ' + REPLACE(f.delete_referential_action_desc, '_', ' ') +
- ' ON UPDATE ' + REPLACE(f.update_referential_action_desc , '_', ' ') collate database_default
- FROM sys.foreign_keys f
- INNER JOIN sys.TABLES t ON f.parent_object_id=t.object_id
- INNER JOIN sys.schemas s ON t.schema_id=s.schema_id
- WHERE t.is_ms_shipped=0;
Script 2. DELETE in proper order
- SET NOCOUNT ON
- GO
- SELECT 'USE [' + db_name() +']';
- ;With a AS
- (
- SELECT 0 AS lvl,
- t.object_id AS tblID
- FROM sys.TABLES t
- WHERE t.is_ms_shipped=0
- AND t.object_id NOT IN (SELECT f.referenced_object_id FROM sys.foreign_keys f)
- UNION ALL
- SELECT a.lvl + 1 AS lvl,
- f.referenced_object_id AS tblId
- FROM a
- INNER JOIN sys.foreign_keys f
- ON a.tblId=f.parent_object_id
- AND a.tblID<>f.referenced_object_id
- )
- SELECT 'Delete from ['+ object_schema_name(tblID) + '].[' + object_name(tblId) + ']'
- FROM a
- GROUP BY tblId
- ORDER BY Max(lvl),1
Note. Don't forget to modify max column display size parameter in SSMS and preferably execute it in "result in text" mode (Ctrl-T)




LTD Social Sitings
Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.