declare cur_table Cursor local FORWARD_ONLY For
Select so.name Table_name, --表名字
sc.name Iden_Column_name, --自增字段名字
ident_current(so.name) curr_value, --自增字段当前值
ident_incr(so.name) incr_value, --自增字段增长值
ident_seed(so.name) seed_value --自增字段种子值
from sysobjects so ,syscolumns sc where so.id = sc.id and columnproperty(sc.id, sc.name, 'IsIdentity') = 1 and so.XTYPE='U'
open cur_table
----声明变量
declare @tableId numeric(18, 0)--表中目前的种子
declare @columnName nvarchar(500)--自增列名
declare @tableSeed numeric(18, 0)--自增字段种子值
declare @tableName nvarchar(500)--表名
declare @incr_value int --步长
declare @tableSeedSQL nvarchar(1000)--动态语句
declare @prams nvarchar(1000)--参数
set @prams='@p numeric(18, 0) output,@tableId numeric(18, 0)'
fetch next from cur_table into @tableName,@columnName, @tableId,@incr_value, @tableSeed
while @@FETCH_STATUS=0
begin
set @tableSeed=0
--声明变量,查询大于种子的偶数
set @tableSeedSQL='select @p= MAX('+@columnName+') from '+quotename(@tableName)+' where '+@columnName+'%2=0 and '+@columnName+' >@tableId'
exec sp_executesql @tableSeedSQL,@prams,@p=@tableSeed output,@tableId=@tableId
--如果没有大于种子的偶数,目标种子为当前种子
if(@tableSeed is null or @tableSeed=0)
set @tableSeed=@tableId
--设置目标种子为偶数
if(@tableSeed%2=1)
set @tableSeed=@tableSeed+1
DBCC CHECKIDENT(@tableName,RESEED,@tableSeed)
fetch next from cur_table into @tableName,@columnName, @tableId,@incr_value, @tableSeed
end
close cur_table
deallocate cur_table