Question : Reseed All tables in db using DBCC CHECKIDENT in one command

We have a couple of databases that we are going to want to reseed the identity fields on about 100 tables to their current high record.

The reason for this is that we want to move a peer database to the "master" and the identity fields have not been incremented properly.

Is there a means of doing this for all tables in a database instead of doing each individual table one at a time?

Thanks

Answer : Reseed All tables in db using DBCC CHECKIDENT in one command

The code is below. Just uncomment the exec (and comment out the print, if desired).
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
set nocount on

declare @tables table (
  id int identity,
  tablename sysname,
  columnName sysname
)

declare @counter int
declare @count int
declare @newseed nvarchar(20)
declare @tablename sysname
declare @columnname sysname
declare @sql varchar(max)
declare @sqlex varchar(max)
declare @sqlMax nvarchar(max)
declare @sqlMaxEx nvarchar(max)
DECLARE @pvalue     VARCHAR(250)
DECLARE @param      NVARCHAR(250)

set @sql = 'DBCC CHECKIDENT (''@table'', RESEED, @value)'
set @sqlMax = 'SELECT @value=MAX(@pkfield) FROM @table'
SET @param = '@value VARCHAR(250) OUTPUT'
 
insert into @tables
select DISTINCT TABLE_NAME, COLUMN_NAME
from INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = 'dbo'
and COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') = 1
order by TABLE_NAME
select @count = @@ROWCOUNT

set @counter = 1
while @counter <= @count begin
  select @tablename = tablename, @columnname = columnName
    from @tables
    where id = @counter
  set @sqlMaxEx = REPLACE(REPLACE(@sqlmax, '@table', @tablename), '@pkfield', @columnname)
  print @sqlmaxex
  
  EXECUTE SP_EXECUTESQL @sqlMaxEx, @param, @value = @pvalue OUTPUT
  
  select @newseed = ISNULL(cast(@pvalue as int), 0) + 1
  set @sqlex = REPLACE(REPLACE(@sql, '@table', @tablename ), '@value', @newseed)
  print @sqlex
  --exec (@sqlex)
  set @counter = @counter + 1
end
Random Solutions  
 
programming4us programming4us