Tuesday, November 29, 2011

TSQL Delete All Data

So you want to delete all the contents of the tables in your MS SQL database. You could drop and create the database. You could also drop and create the tables within the database. Then, you could iterate through all the tables in the INFORMATION_SCHEMA and delete all the rows with a TSQL script.

Here is the script I used:

USE [YourDatabase];
GO
SET NOCOUNT ON;
DECLARE @MyTableName varchar(100);

DECLARE MyCursor CURSOR
  FOR SELECT DISTINCT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
  WHERE TABLE_CATALOG = 'YourDatabase' AND TABLE_SCHEMA = 'dbo';
OPEN MyCursor;
FETCH NEXT FROM MyCursor INTO @MyTableName;

WHILE @@FETCH_STATUS = 0
BEGIN
  EXEC ('DELETE FROM ' + @MyTableName);
  FETCH NEXT FROM MyCursor INTO @MyTableName;
END;
CLOSE MyCursor;
DEALLOCATE MyCursor;