Skip to main content

Easiest / fastest way to Delete ALL records in a Database

One of the very common activities a SQL developer face is to flush records from ALL the tables in their development database.

Though “Delete” and “Truncate” commands can be used to flush records in a table the issue is we can’t use them directly if we have constraints attached to some of the tables.

One of the solutions is to “Delete” records in the tables in an orderly fashion. Like, “Delete” the child table first and then the parent table. As long as there are limited number of tables in the Database this solution is more than enough. But for those databases where there are lots of tables with constraints this solution would be pretty tough to implement. In those cases, try out my solution which I have explained later in this article.

Code snippet to reproduce the foreign key conflict error:

Create Table TruncateTblDemo
(
[Sno] int identity,
[FirstName] varchar(50),
[SalaryBandID] int
)
Go

Create Table TruncateTblDemo_SalaryBand
(
[BandID] int identity primary key,
[BandName] varchar(50)
)
Go

Alter
table TruncateTblDemo Add
Constraint [FK_TruncateTblDemo_TruncateTblDemo_SalaryBand] Foreign Key
(
[SalaryBandID]
)
References [TruncateTblDemo_SalaryBand]
(
[BandID]
)
Go

Insert into TruncateTblDemo_SalaryBand Values ('Analyst')
Insert into TruncateTblDemo_SalaryBand Values ('Sr. Analyst')
Insert into TruncateTblDemo_SalaryBand Values ('Module Lead')
Insert
into TruncateTblDemo_SalaryBand Values ('Technical Lead')
Go

Insert
into TruncateTblDemo Values ('Vadivel', 1)
Insert into TruncateTblDemo Values ('Sailakshmi', 2)
Go

/*
The below code would throw an error message saying "it cannot delete / truncate because it is being referenced by a FOREIGN KEY constraint."
*/

Truncate
table TruncateTblDemo_SalaryBand
Delete from TruncateTblDemo_SalaryBand

Usual or Normal Solution

Delete
from TruncateTblDemo -– Child Table
Delete from TruncateTblDemo_SalaryBand –- Parent Table

Easiest Solution which would work for any [SQL Server] Database design

This solution is a 3 step process.

  1. Disable all constraints
  2. Delete or Truncate data
  3. Enable Constraints back

Code snippet

Alter Procedure usp_FlushRecords_AllTables
As

/*********************************************************
Stored Procedure: usp_FlushRecords_AllTables
Creation Date: 07/24/2006
Written by: Vadivel Mohanakrishnan

P
urpose: Delete ALL records within ALL the tables in a DB with ease.
Test: Exec usp_FlushRecords_AllTables **********************************************************/

Set
nocount on

Exec sp_MSForEachTable 'Alter Table ? NoCheck Constraint All'

Exec
sp_MSForEachTable
'
If ObjectProperty(Object_ID(''?''), ''TableHasForeignRef'')=1
Begin
-- Just to know what all table used delete syntax.
Print ''Delete from '' + ''?''
Delete From ?
End
Else
Begin
-- Just to know what all table used Truncate syntax.
Print ''Truncate Table '' + ''?''
Truncate Table ?
End
'

Exec
sp_MSForEachTable
'Alter Table ? Check Constraint All'

Points to note

  1. This stored procedure can be used against any SQL Server database design.
  2. Try this out in your local or development box ONLY.
  3. “sp_MSForEachTable” is an undocumented stored procedure of Microsoft
  4. You could save this SP within “Model” database. That way, all future databases which are created on that server would by default get this SP in it.
Hope this helps!

Technorati tags: , ,

Comments

Anonymous said…
Nice, thanks for the query
Anonymous said…
Thanks for the query - very useful to get back to a bare schema.

Suggestion:
To see progress, because PRINT has to wait until the buffer is full before it will show you "progress" in the messages tab, try:

EXEC sp_MSForEachTable '
DECLARE @MSG nvarchar(4000)
If ObjectProperty(Object_ID(''?''), ''TableHasForeignRef'') = 1
BEGIN
-- Just to know which tables used delete syntax.
SET @MSG = ''DELETE FROM '' + ''?''
RAISERROR(@MSG,0,1) WITH NOWAIT

DELETE FROM ?
END
ELSE
BEGIN
-- Just to know which tables used Truncate syntax.
SET @MSG = ''TRUNCATE TABLE '' + ''?''
RAISERROR(@MSG,0,1) WITH NOWAIT

TRUNCATE TABLE ?
End
'

Sorry, don't know HTML or I'd have preserved the formatting :(
Anonymous said…
Excellent solution.
Thanks to both of you.
Made short work of what would have been an onerous task on a big database.
Cheers.
Ed.
Anonymous said…
That was real neat! Thanks...saved a lot of my time and one more egg in my basket of knowledge!!!! :) :)

Sapnah
Anonymous said…
Great work! This helped me a lot in clearing the database to the bare schema.
Thanks
Siva
Anonymous said…
Careful with this. It deletes data from the system tables as well. This means that it wrecks database diagrams (dbo.sysdiagrams) for one thing.
Anonymous said…
Stops the script from deleting the contents of the system databases such as sysdiagrams.

Set nocount on

Exec sp_MSForEachTable 'Alter Table ? NoCheck Constraint All'

EXEC sp_MSForEachTable '
DECLARE @MSG nvarchar(4000)
If CHARINDEX(''[dbo].[sys'', ''?'') = 0
BEGIN
If ObjectProperty(Object_ID(''?''), ''TableHasForeignRef'') = 1
BEGIN
-- Just to know which tables used delete syntax.
SET @MSG = ''DELETE FROM '' + ''?''
RAISERROR(@MSG,0,1) WITH NOWAIT

DELETE FROM ?
END
ELSE
BEGIN
-- Just to know which tables used Truncate syntax.
SET @MSG = ''TRUNCATE TABLE '' + ''?''
RAISERROR(@MSG,0,1) WITH NOWAIT

TRUNCATE TABLE ?
End
End
'

Exec sp_MSForEachTable 'Alter Table ? Check Constraint All'
Anonymous said…
Woooo!! Indeed cool stuff. thanks a lot
Vadivel said…
Follow up post on this topic is here - http://vadivel.blogspot.com/2011/10/how-to-truncate-all-tables-in-sql.html
Anonymous said…
Your stored procedure removes alse the database diagrams from the DB :-( How can I preserve them?

Popular posts from this blog

Script table as - ALTER TO is greyed out - SQL SERVER

One of my office colleague recently asked me why we are not able to generate ALTER Table script from SSMS. If we right click on the table and choose "Script Table As"  ALTER To option would be disabled or Greyed out. Is it a bug? No it isn't a bug. ALTER To is there to be used for generating modified script of Stored Procedure, Functions, Views, Triggers etc., and NOT for Tables. For generating ALTER Table script there is an work around. Right click on the table, choose "Modify" and enter into the design mode. Make what ever changes you want to make and WITHOUT saving it right click anywhere on the top half of the window (above Column properties) and choose "Generate Change Script". Please be advised that SQL Server would drop actually create a new table with modifications, move the data from the old table into it and then drop the old table. Sounds simple but assume you have a very large table for which you want to do this! Then it woul

AWS fatal error: An error occurred (400) when calling the HeadObject operation: Bad Request

While using AWS and trying to copy a file from a S3 bucket to my EC2 instance ended up with this error message. Command Used: aws s3 cp s3://mybucketname/myfilename.html /var/www/html/ Error: fatal error: An error occurred (400) when calling the HeadObject operation: Bad Request The error goes off if we add the region information to the command statement. I am using Asia Pacific (Mumbai) so used ap-south-1 as the region name. Modified Command: aws s3 cp s3://mybucketname/myfilename.html /var/www/html/ --region ap-south-1

[Non Tech] Want to know the recipe for Omelette :)

Fed up with Bread - Jam and Curd Rice, today i wanted to eat Omelette. Interesting part is I wanted to cook it myself :) So in the first picture you see all the items which are needed for preparing an Omelette. When I had a closer look at the eggs I see that almost all the eggs are broken. But believe me when I bought it couple of days back it was in perfect condition! I was wondering whether the eggs have become rotten or pretty old to consume! I tried taking an egg and break it but couldn't break it at all :) Since I have kept in the freezer all the eggs have frozen and looked like a iron ball :) After trying for few minutes of trying i removed the shell of the egg and then kept that iron ball :) into a bowl and placed it within Oven. I heated it for 1 minute and checked. It melted only to a limit. So i just set it for another 2 minutes and checked it later. It has melted but the part of the egg white has become a Omelette :( I didn't leave it there. I took the bowl out of