views:

136

answers:

2

How I can delete all records from all tables of my database? Can I do it with one SQL command or I need for one SQL command per one table?

+13  A: 

Usually I will just use the undocumented proc sp_MSForEachTable

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

EXEC sp_MSForEachTable 'TRUNCATE TABLE ?' 
GO 

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

See also: Delete all data in database (when you have FKs)

SQLMenace
That's awesome.
Robert Harvey
I don't think this works. Looks like Kalen Delaney was inadvertently responsible for starting this idea off. [Here she clarifies](http://www.eggheadcafe.com/software/aspnet/29927698/cant-truncate-table.aspx) "you have to drop the referencing constraint in order to truncate the table."
Martin Smith
Martin I just ran it 2 seconds ago in the Adventureworks DB without a problem
SQLMenace
It definitely does not work for me here. `create database testing; GO use testing; create table t1 (i int primary key) create table t2(i int primary key,p int references t1)`
Martin Smith
+3  A: 

It is usually much faster to script out all the objects in the database, and create an empty one, that to delete from or truncate tables.

AlexKuznetsov