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

Registry manipulation from SQL

Registry Manupulation from SQL Server is pretty easy. There are 4 extended stored procedure in SQL Server 2000 for the purpose of manupulating the server registry. They are: 1) xp_regwrite 2) xp_regread 3) xp_regdeletekey 4) xp_regdeletevalue Let us see each one of them in detail! About xp_regwrite This extended stored procedure helps us to create data item in the (server’s) registry and we could also create a new key. Usage: We must specify the root key with the @rootkey parameter and an individual key with the @key parameter. Please note that if the key doesn’t exist (without any warnnig) it would be created in the registry. The @value_name parameter designates the data item and the @type the type of the data item. Valid data item types include REG_SZ and REG_DWORD . The last parameter is the @value parameter, which assigns a value to the data item. Let us now see an example which would add a new key called " TestKey ", and a new data item under it called TestKeyValue :

Screen scraping using XmlHttp and Vbscript ...

I wrote a small program for screen scraping any sites using XmlHttp object and VBScript. I know I haven't done any rocket science :) still I thought of sharing the code with you all. XmlHttp -- E x tensible M arkup L anguage H ypertext T ransfer P rotocol An advantage is that - the XmlHttp object queries the server and retrieve the latest information without reloading the page. Source code: < html > < head > < script language ="vbscript"> Dim objXmlHttp Set objXmlHttp = CreateObject("Msxml2.XMLHttp") Function ScreenScrapping() URL == "UR site URL comes here" objXmlHttp.Open "POST", url, False objXmlHttp.onreadystatechange = getref("HandleStateChange") objXmlHttp.Send End Function Function HandleStateChange() If (ObjXmlHttp.readyState = 4) Then msgbox "Screenscrapping completed .." divShowContent.innerHtml = objXmlHttp.responseText End If End Function </ script > < head > < body > &l

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