我已经编写了将所有表的标识重置为1的代码,但在某些表中,标识不会重置为1,否则将重置为0或2或其他数字 这是我的代码
declare @Count int
declare @C int
declare @Str varchar(20)
set @C=1
set @Count=(select COUNT(*) TABLE_NAME from INFORMATION_SCHEMA.TABLES )
while @C<@Count
BEGIN
with Records AS(select row_number() over(order by TABLE_NAME) as 'row1', *
from INFORMATION_SCHEMA.TABLES)
select @Str= TABLE_NAME from records
where row1=@C
set @C=@C+1
DBCC CHECKIDENT (@Str , reseed, 0)
END
答案 0 :(得分:0)
gbn。已经说过如果表创建后没有插入任何行,或者使用TRUNCATE TABLE语句删除了所有行,则在运行DBCC CHECKIDENT后插入的第一行使用new_reseed_value作为标识。否则,插入的下一行使用new_reseed_value +当前增量值但是我们想要将所有身份重置为1.任何人都这样做了吗?
答案 1 :(得分:0)
假设您的所有表实际上都是空的,这应该适合您。它循环遍历定义了IDENTITY(1,1)
的所有表,并将它们重新设置为除了那些从未插入行或已被截断且不需要重新设置的表。
DECLARE @Name NVARCHAR(1000)
DECLARE @C1 AS CURSOR;
SET @C1 = CURSOR FAST_FORWARD
FOR SELECT Quotename(Object_schema_name(object_id)) + '.'
+ Quotename(Object_name(object_id))
FROM sys.identity_columns
WHERE Objectpropertyex(object_id, 'IsUserTable') = 1
AND seed_value = 1
AND increment_value = 1
AND last_value IS NOT NULL;
OPEN @C1;
FETCH NEXT FROM @C1 INTO @Name;
WHILE @@FETCH_STATUS = 0
BEGIN
DBCC CHECKIDENT (@Name, reseed, 0)
FETCH NEXT FROM @C1 INTO @Name;
END