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

Delete the data from all tables In Database-Simple Sql Server Query!

USE TEST
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable '
IF OBJECTPROPERTY(object_id(''?''), ''TableHasForeignRef'') = 1
DELETE FROM ?
else
TRUNCATE TABLE ?
'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO