SQL Server - Delete Records From All Tables


By Bihag Thaker
Printer Friendly Version
View My Articles

  

Sometimes it is needed to delete all the records from all the tables resetting the SEED value of identity fields at the same time. This article will show you how we can achieve this task with the help of user defined stored procedure.



Sometimes it is exercised to empty all the tables in a database by deleting all the records from all the tables or by truncating every table in a database. This is indeed needed while we are developing a real life application and playing around with the database in order to carry out testing. But as it seems to be this task is not that much easy and trivial because usually there exists so many Primary Key-Foreign Key relationships between parent and child tables at many levels in such types of applications. If you start deleting records in improper sequence, records might not be deleted from every table successfully as depending upon the option ON DELETE CASCADE set on foreign tables records might not be deleted from parent tables as long as their corresponding child records are existing and you don’t want to be warned by SQL Server with the error message “The DELETE statement conflicted with the REFERENCE constraint…” every time you try to delete the records from some tables and at the same time you also don’t want to remember the complete hierarchy of parent-child relationships between all the tables in order to carry out delete operation in proper sequence. While emptying tables, sometimes we need to reset the SEED value of identity fields which the TRUNCATE command does it for us and DELETE command does not. But unfortunately TRUNCATE also does not work because as long as the foreign key constraints are existing, parent tables can’t to be truncated. Keeping all these in mind, I needed to create a solution which solves this problem.

I wrote the following stored procedure that performs this task for us. Just create this stored procedure in the database for which the tables need to be emptied.

-----------------------

Create Procedure dbo.sp_EmptyAllTables (@ResetIdentity Bit)

As

Begin

    Declare @SQL VarChar(500)

    Declare @TableName VarChar(255)

    Declare @ConstraintName VarChar(500)

    Declare curAllForeignKeys SCROLL CurSor For Select Table_Name,Constraint_Name From Information_Schema.Table_Constraints Where Constraint_Type='FOREIGN KEY'

    Open curAllForeignKeys

 

    Fetch Next From curAllForeignKeys INTO @TableName,@ConstraintName

    While @@FETCH_STATUS=0

    Begin

        Set @SQL = 'ALTER TABLE ' + @TableName + ' NOCHECK CONSTRAINT ' + @ConstraintName

        Execute(@SQL)

        Fetch Next From curAllForeignKeys INTO @TableName,@ConstraintName

    End

 

  

    Declare curAllTables Cursor For Select Table_Name From Information_Schema.Tables Where TABLE_TYPE='BASE TABLE'

    Open curAllTables

 

    Fetch Next From curAllTables INTO @TableName

    While @@FETCH_STATUS=0

    Begin

        Set @SQL = 'DELETE FROM ' + @TableName

            If @ResetIdentity = 1 AND OBJECTPROPERTY (OBJECT_ID(@TableName),'TableHasIdentity')=1

                  Set @SQL = @SQL + '; DBCC CHECKIDENT(''' + @TableName + ''',RESEED,0)'             

           

        Execute(@SQL)

        Fetch Next From curAllTables INTO @TableName

    End

 

  

    Fetch First From curAllForeignKeys INTO @TableName,@ConstraintName

    While @@FETCH_STATUS=0

    Begin

        Set @SQL = 'ALTER TABLE ' + @TableName + ' CHECK CONSTRAINT ' + @ConstraintName

        Execute(@SQL)

        Fetch Next From curAllForeignKeys INTO @TableName,@ConstraintName

    End

 

    Close curAllTables  

    Deallocate curAllTables

 

    Close curAllForeignKeys

    Deallocate curAllForeignKeys  

End

-----------------------

The above stored procedure accepts one parameter (@ResetIdentity) which can be either 0 or 1 depending upon whether we need to reset the SEED of identity fields or not (1 for resetting otherwise 0). To empty all the tables while resetting the SEED value of identity fields at the same time, just call this store procedure in the following way:

sp_EmptyAllTables 1

I hope this technique will save some of your time needed to perform the task of emptying all the tables in a database.



button
 
Article Discussion: How to empty all the tables in a database?
Bihag Thaker posted at 18-Aug-08 06:23
Original Article

promotion
Silverlight    WPF    WCF    WWF    LINQ   
JavaScript    AJAX    ASP.NET    XAML   
C#    VB.NET    VB 6.0    GDI+    IIS    XML   
.NET Generics    Anonymous Methods    Delegate   
Visual Studio .NET    Expression Blend    Virus   
Windows Vista    Windows XP    Windows Update   
Windows 2003 Server    Windows 2008 Server   
SQL Server    Microsoft Excel    Microsoft Word   
SharePoint    BizTalk    Virtual Earth   
.NET Compact Framework    Web Service   

"Everything" RSS / ATOM Feed Parser
How to send and receive messages through message queuing in .Net
How to Read text file as database
SQL Server 2005 Paging Performance Tip
Display code of web page.
Fully Scalable Excel File Importer class for .net using Microsoft Jet driver
Generic Chart Color Manager class that can be used for any charts
Helper class to style the infragistics wingrid
Using Reflection to detemine as Assembly Info in and out.
Helper class to play with Window (Owners and position)
Resolving displayname from the culture using the XmlLanguage and LanguageSpecificStringDictionary class
Manipulate file attributes in VB.NET
Forms Based Authentication Filtered Content Editor for SharePoint
How to create a Tree View of the Windows Folder and extract all the file-folder info.
How to use AssemblyInfo.cs file in win forms to provide much needed information on Assemblies
Sorting In Datagrid
Helper class to work with NativeMethods in the native api's
Silverlight Line Of Business Applications With Offline WPF Versions
C# : Database monitoring system using XML file
C# : Adding ComboBox to ListView SubItem
Sum of Numbers Captcha: Keeping it Simple
C# Create a Piechart for the specified Hard Disk Drive Utilization
Extension Methods for DataSet and DataTable that makes tasks easier
Accessing IIS Hosted WCF Services from PHP
Helper class that provides most commonly used Extension Methods for DateTime object
Helper class to work with a Status Bar in WPF.
Finding Unmatched Records in Dataset Tables Using Linq
Silverlight Toolkit: Autocomplete TextBox Stock Symbols and Chart
COOL Auto Complete textbox using javascript
Creating a Serializable Log Entry for Microsoft Enterprise Library to log to a Database
ASP.NET Searching Values in Datagrid