SQL Server Truncate All Tables
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




