Thursday, July 1, 2010

Scary Script

This has to be one of the scariest scripts I have ever seen...my co-worker sent it to me. It is used to delete all data from all tables in a given database.


-- change me!
USE [MyDatabase]

-- don't touch below here

-- disable all constraints
EXEC sp_MSForEachTable "ALTER TABLE ? NOCHECK CONSTRAINT all"

-- delete data in all tables
EXEC sp_MSForEachTable "DELETE FROM ?"

-- enable all constraints
EXEC sp_MSForEachTable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

-- reseed identity columns
EXEC sp_MSForEachTable "DBCC CHECKIDENT ( '?', RESEED, 0)"

-- check to see if any tables have rows
-- this could probably be handled better
CREATE TABLE #CheckRows (TableName VARCHAR(60), NumRows INT)
EXEC sp_MSforeachtable "INSERT INTO #CheckRows SELECT '?',COUNT(1) FROM ?"
SELECT * FROM #CheckRows WHERE NumRows > 0
DROP TABLE #CheckRows

1 comment: