Monday, July 27, 2009

RESEED All Identity Column in all tables of a Database

IF EXISTS(SELECT *FROM SYS.PROCEDURES WHERE NAME='SP_RESEEDIdentityColumn')
BEGIN
DROP PROC SP_RESEEDIdentityColumn
END
GO
CREATE PROC SP_RESEEDIdentityColumn
@RESEEDVALUE INT=0
AS
BEGIN
DECLARE CURRESEED CURSOR
FOR
SELECT NAME FROM SYS.TABLES

DECLARE @TABNAME VARCHAR(225),@SQL NVARCHAR(225)

OPEN CURRESEED
FETCH NEXT FROM CURRESEED INTO @TABNAME
WHILE @@FETCH_STATUS=0
BEGIN
SET @SQL ='DBCC CHECKIDENT('+@TABNAME+',RESEED,'+@RESEEDVALUE+')'
EXEC(@SQL)
FETCH NEXT FROM CURRESEED INTO @TABNAME
END
END

CLOSE CURRESEED
DEALLOCATE CURRESEED
GO


--Here if you are not specified param value it reseed from 0
EXECUTE SP_RESEEDIdentityColumn

--Here if you are not specified param value it reseed from 1
EXECUTE SP_RESEEDIdentityColumn 1

No comments: