SQL Bulk Delete user tables (delete all foreign key constraints before deleting all tables)

Source: Internet
Author: User

--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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.