Problem statement
One of my project assignments was to clean an entire database, in other words delete all the data from all the tables of the database. My database has more than 800 tables so it was not possible to write a delete query on each and every table and each table having many constraints like primary key and foreign key.
So manually writing a query is a very tedious job.
Solution
I have found two ways to delete all the table data within a database. In this article I will explain each way one by one.
1. Using Undocumented Stored Procedure: sp_MSForEachTable
The Stored Procedure “sp_MSforeachtable” allows us to easily process some code against each and every table in a single database. It means that it is used to process a single T-SQL command or a number of different T-SQL commands against every table in the database.
Using the following procedure we can delete all the data from all the tables of a single database.
Step 1: Disable all constraints on the database
Step 2: Do a Delete or truncate operation on each table of the database
Step 3: Enable all constrains on the database
2. Using INFORMATION_SCHEMA.TABLES and INFORMATION_SCHEMA.TABLE_CONSTRAINTS system tables
The INFORMATION_SCHEMA.TABLES view allows us to get information about all the tables and views within the database. INFORMATION_SCHEMA.TABLE_CONSTRAINTS returns the information about the table constraints in the current database. Using the following procedure we can delete all the data from all the tables in the database.
Step 1: Determine all child tables and tables that have no relations. Perform the delete operation on those tables.
Step 2: Determine all parent tables and perform the delete operation on these tables and also reset the identity column
Summary
Using the methoda described above, we can delete all the data from all the tables of a single database.
Not a member yet? Register now
Are you a member? Login now