T-SQL - RESEED identity if the table has zero records

The below code reseeds identity value if the table has zero record count.

--Temp tables to hold tablenames & recordcounts

CREATE TABLE ##TableRowCounts([TableName] VARCHAR(128), [RowCount] INT) ;
CREATE TABLE ##TableNoRowCounts(RN INT IDENTITY(1,1),[TableName] VARCHAR(128), [RowCount] INT) ;

INSERT INTO ##TableRowCounts ([TableName], [RowCount])
EXEC sp_MSforeachtable 'SELECT ''?'' [TableName], COUNT(*) [RowCount] FROM ?' ;

INSERT ##TableNoRowCounts
SELECT [TableName], [RowCount] FROM ##TableRowCounts
WHERE [RowCount] = 0

DECLARE @i TINYINT = 1,
        @query NVARCHAR(MAX),
        @tblname NVARCHAR(MAX)

WHILE @i <= (SELECT COUNT(1) FROM ##TableNoRowCounts)

BEGIN

SET @tblname = (SELECT [TableName] FROM ##TableNoRowCounts WHERE RN = @i)
SET @tblname = REPLACE(REPLACE(REPLACE(@tblname,'[dbo].',''),']',''),'[','')
--RESEED Identity
SET @query = 'DBCC CHECKIDENT ('+@tblname+', RESEED, 0)'
EXEC (@query)
SET @i = @i + 1

END

--Dropping temp tables
DROP TABLE ##TableRowCounts
DROP TABLE ##TableNoRowCounts 
 


Reference :http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/0f0d17ac-1db9-4599-9852-cc3628f169e5
 

No comments: