标签:
Declare @IdentityTable sysname,
@IdentityColumn sysname,
@TotalRows int,
@i int,
@Iden int,
@Sql varchar(4000)
SET NOCOUNT ON
--标识列表
Create Table #IDENTITY_Table
(
SeqID_int int identity(1,1),
IDENTITY_TABLE sysname null,
IDENTITY_COLUMN sysname null,
IDENTITY_MAX int null default(0)
)
Create Table #IDENTITY_Table_Column_Value
(
IDENTITY_MAX int
)
Insert Into #IDENTITY_Table(IDENTITY_TABLE,IDENTITY_COLUMN)
Select --‘select IDENT_CURRENT(‘‘‘ + Obj.name + ‘‘‘)‘,
Obj.name,
Col.name
From sys.tables AS Obj left outer join sys.columns AS Col on Obj.object_id = Col.object_id
and Col.is_identity = 1
Where Obj.type = ‘U‘
and objectproperty(object_id(Obj.name),‘TableHasIdentity‘) = 1;
Set @TotalRows = @@ROWCOUNT;
Set @i = 1;
--循环得到每一个标识列表,然后更新为当前最大标识列值
WHILE(@i <= @TotalRows)
Begin
Select @IdentityTable = IDENTITY_TABLE,
@IdentityColumn = IDENTITY_COLUMN
From #IDENTITY_Table
Where SeqID_int = @i;
Set @Sql = ‘Insert into #IDENTITY_Table_Column_Value‘ + char(10) + ‘select max(‘ + @IdentityColumn + ‘) + 1 from ‘ + @IdentityTable;
--print @Sql
EXEC (@Sql);
Select @Iden = IDENTITY_MAX from #IDENTITY_Table_Column_Value;
Set @Iden = IsNull(@Iden,1)
update #IDENTITY_Table
set IDENTITY_MAX = @Iden
where IDENTITY_TABLE = @IdentityTable;
--DBCC CHECKIDENT( @IdentityTable, RESEED, @Iden )
--print @IdentityTable + ‘,‘ + cast(@Iden as varchar(10))
Set @i = @i + 1;
Set @Iden = 0
Set @Sql = ‘‘
truncate table #IDENTITY_Table_Column_Value
End
/*
Truncate Table #IDENTITY_Table;
Drop Table #IDENTITY_Table;
truncate table #IDENTITY_Table_Column_Value
drop table #IDENTITY_Table_Column_Value
*/
SET NOCOUNT OFF
-----------------------------------------------
--select ‘DBCC CHECKIDENT(‘ + IDENTITY_TABLE + ‘,RESEED, ‘ + cast (IDENTITY_MAX as varchar(10)) + ‘)‘ from #IDENTITY_Table
select * from #IDENTITY_Table
标签:
原文地址:http://www.cnblogs.com/xishi/p/5479071.html