How to delete all data in SQL Server

Source: Internet
Author: User

A lot of dirty data is inserted in the database, and it is like a haystack if you want to find and delete it one by one. When the useful data of a database is backed up, you can first Delete the data of all tables to make it a database with only a framework, and then restore the backup data.

How can we delete all the data? When deleting tables one by one, you must encounter various troubles such as foreign key constraints and triggers. Obviously, you can remove the foreign key constraint and trigger before deleting the table. See the following SQL statement.

 
Exec sp_msforeachtable 'alter table? Nocheck constraint all 'exec sp_msforeachtable 'alter table? Disable trigger all 'exec sp_msforeachtable 'Delete from? 'Exec sp_msforeachtable' alter table? Check constraint all 'exec sp_msforeachtable 'alter table? Enable trigger all'

Sp_msforeachtable is a stored procedure that has never been made public by the Microsoft System database, and sp_msforeachdb is another stored procedure.

The first and second statements above are used to unbind and disable triggers, the third statement is to delete data from all data tables, and the fourth and fifth statements are the recovery constraints and triggers.

Write the preceding statement as a system stored procedure.

Use master
Create procedure sp_deletealldata
As
Exec sp_msforeachtable 'alter table? Nocheck constraint all'
Exec sp_msforeachtable 'alter table? Disable trigger all'
Exec sp_msforeachtable 'delete from? '
Exec sp_msforeachtable 'alter table? Check constraint all'
Exec sp_msforeachtable 'alter table? Enable trigger all'
Go

References:

1. http://www.knowsky.com/541311.html

2. http://hi.baidu.com/windy8848/blog/item/f814b57e25fb77300cd7daef.html

Related Article

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.