Thursday, April 17, 2008

A quick snippet to delete all data in sql server 2005+

Note: this is a piece of code I've lost and rewitten a few times now, maybe you'll find it handy someday.

sp_msforeachtable 'ALTER TABLE ? NOCHECK CONSTRAINT all';
go
sp_msforeachtable 'ALTER TABLE ? DISABLE TRIGGER all';
go
sp_MSForEachTable 'delete from ?', '?', null, null, 'and o.name not like (''system_%'')';
go
sp_msforeachtable 'ALTER TABLE ? CHECK CONSTRAINT all';
go
sp_msforeachtable 'ALTER TABLE ? Enable TRIGGER all';
go
What it does is disable all the relational constraints and triggers in the database, then wipes the tables clean, and re-enables the constraints/triggers at the end. Very fast, even compared with the TRUNCATE command.
For some reason, every command needs to be in a batch, hence the 'go' statements.

0 Comments:

Post a Comment

<< Home