Welcome to Office Zealot Sign in | Join | Help

T-SQL Trick for Deleting All Data in Your Database

I came across a great tip in Roman Rehak's blog (http://www.sqljunkies.com/WebLog/roman/archive/2006/03/08/18620.aspx) on how to use simple t-sql to delete all the data in all the tables of a database.  I've added this to my SQL toolbox for two reasons:

(1) It's a quick and easy way to clear out bogus/bad data that I may have entered while building a new application.  This is especially helpful if you use referential integrity and use parent/child table dependencies.

(2) I tend to due a lot of ad hoc security evangelism while working with customers.  One of the items I often highlight is that too many folks have Enterprise Manager (SQL 2000) or Management Studio (SQL 2005) on their desktop and they have too much power in respective databases.  The response I often receive is “That's not a big deal.  What damage can someone possibly do?”  Well, give me 5 seconds on someone's machine with this t-sql and (poof!) your production data can be gone!  Granted, I would never do it but this t-sql clearly shows that it can be done quickly.

Here's the t-sql... Thanks Roman!

-- disable referential integrity
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO

EXEC sp_MSForEachTable '
 IF OBJECTPROPERTY(object_id(''?''), ''TableHasForeignRef'') = 1
  DELETE FROM ?
 else
  TRUNCATE TABLE ?
'
GO

-- enable referential integrity again
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO

Published Sunday, March 12, 2006 5:57 AM by Mauro

Comments

Monday, July 31, 2006 1:04 PM by Anonymous

# re: T-SQL Trick for Deleting All Data in Your Database

Will this also remove data from necessary system tables or will my structure remain intact?
Monday, July 31, 2006 1:08 PM by Anonymous

# re: T-SQL Trick for Deleting All Data in Your Database

I have a database that users entered data into last year. They want to start with fresh data this year. I have backed up my database and access to it via the web is denied. What is the best way for me to clear the database of last year's data?
Wednesday, August 09, 2006 4:46 PM by Anonymous

# re: T-SQL Trick for Deleting All Data in Your Database

You may also want your tables to be reseeded to 0 if so I would add:


-- This will reseed each table [don't run this exec if you don't want all your seeds to be reset]
EXEC sp_MSForEachTable '
IF OBJECTPROPERTY(object_id(''?''), ''TableHasIdentity'') = 1
DBCC CHECKIDENT (''?'', RESEED, 0)
'
GO

# SQL - Apagando todos os registros de um banco de dados SQL Server | Tom??s V??squez - Blog

Friday, May 14, 2010 9:11 PM by Gunnar Peipman's ASP.NET blog

# MSSQL: Copying data from one database to another

I have database that has data imported from another server using import and export wizard of SQL Server

# MSSQL: Copying data from one database to another | OOP - Object Oriented Programing

Anonymous comments are disabled