--Delete user tables in bulk
--1. Deleting a FOREIGN KEY constraint
DECLARE C1 Cursor FOR
Select ' ALTER TABLE [' + object_name (parent_obj) + '] drop constraint [' +name+ ']; ‘
From sysobjects
where xtype = ' F '
Open C1
DECLARE @c1 varchar (8000)
FETCH NEXT from C1 to @c1
while (@ @fetch_status =0)
Begin
EXEC (@c1)
FETCH NEXT from C1 to @c1
End
Close C1
DEALLOCATE C1
--2. Deleting a table
DECLARE C2 Cursor FOR
Select ' Drop table [' +name + ']; ‘
From sysobjects
where xtype = ' u '
Open C2
DECLARE @c2 varchar (8000)
FETCH NEXT from C2 to @c2
while (@ @fetch_status =0)
Begin
EXEC (@c2)
FETCH NEXT from C2 to @c2
End
Close C2
DEALLOCATE C2
--Bulk clear the contents of the table:
--1. Disabling FOREIGN KEY constraints
DECLARE C1 Cursor FOR
Select ' ALTER TABLE [' + object_name (parent_obj) + '] nocheck constraint [' +name+ ']; ‘
From sysobjects
where xtype = ' F '
Open C1
DECLARE @c1 varchar (8000)
FETCH NEXT from C1 to @c1
while (@ @fetch_status =0)
Begin
EXEC (@c1)
FETCH NEXT from C1 to @c1
End
Close C1
DEALLOCATE C1
--2. Clearing the contents of a table
DECLARE C2 Cursor FOR
Select ' TRUNCATE TABLE [' +name + ']; ‘
From sysobjects
where xtype = ' u '
Open C2
DECLARE @c2 varchar (8000)
FETCH NEXT from C2 to @c2
while (@ @fetch_status =0)
Begin
EXEC (@c2)
FETCH NEXT from C2 to @c2
End
Close C2
DEALLOCATE C2
--3. Enabling FOREIGN KEY constraints
DECLARE C1 Cursor FOR
Select ' ALTER TABLE [' + object_name (parent_obj) + '] Check constraint [' +name+ ']; ‘
From sysobjects
where xtype = ' F '
Open C1
DECLARE @c1 varchar (8000)
FETCH NEXT from C1 to @c1
while (@ @fetch_status =0)
Begin
EXEC (@c1)
FETCH NEXT from C1 to @c1
End
Close C1
DEALLOCATE C1
SQL Bulk Delete user tables (delete all foreign key constraints first, and then delete all tables)