SQL Server Truncate All Tables

Posted by Joggee | SQL Server 2005, SQL Tips and Tricks | Wednesday 17 September 2008 11:50 am

There was a scenario that I wanted to clear all the data from almost all tables, the first thing came into my mind.I created cursor which generate all the queries for me. I know this will be helpful for everybody.If you have any other solution please share with me.

DECLARE @TableName VARCHAR(256)
DECLARE @varSQL VARCHAR(512)

DECLARE @getTBName CURSOR SET @getTBName = CURSOR FOR SELECT name FROM sys.Tables WHERE NAME NOT LIKE ‘Category’

OPEN @getTBName FETCH NEXT FROM @getTBName INTO @TableName

WHILE @@FETCH_STATUS = 0
BEGIN
SET @varSQL = ‘Truncate table ‘+ @TableName + ”
– EXEC (@varSQL)
PRINT (@varSQL)
FETCH NEXT FROM @getTBName INTO @TableName

ENDCLOSE @getTBName
DEALLOCATE @getTBName

Joggee