Friday, June 29, 2012

Reset all identities in SQL Server


As using query from http://beyondrelational.com/justlearned/posts/169/get-all-the-tables-and-columns-having-identity-propertly-sql-server.aspx , herewith script to reset all identities for all tables in database.
01.DECLARE @sql varchar(8000)
02.DECLARE @tbl VARCHAR(4000)
03.DECLARE @col VARCHAR(4000)
04.DECLARE c_ident cursor FAST_FORWARD FOR 
05.SELECT table_name,column_name
06.FROM
07.INFORMATION_SCHEMA.COLUMNS
08.WHERE
09.COLUMNPROPERTY -- checking for identity = 1
10.(
11.OBJECT_ID(QUOTENAME(table_schema) + '.' + QUOTENAME(table_name))
12.,column_name
13.,'isidentity'
14.) = 1
15.OPEN c_ident
16.FETCH NEXT FROM c_ident INTO @tbl,@col
17.WHILE @@FETCH_STATUS = 0
18.BEGIN
19.SET @SQL = '
20.DECLARE @RESEEDIDENT BIGINT
21.SET @RESEEDIDENT  = (select ISNULL(max('+@col+'),0) from '+@tbl+')
22.DBCC CHECKIDENT ( '''+@tbl+''', RESEED, @RESEEDIDENT )
23.'
24.PRINT (@SQL)
25.EXEC(@SQL)
26.FETCH NEXT FROM c_ident INTO @tbl,@col
27.END
28.CLOSE c_ident
29.DEALLOCATE c_ident

source: http://beyondrelational.com/modules/1/justlearned/388/tips/8593/reset-all-identities-in-sql-server.aspx

No comments: