首页 > 解决方案 > 将标识列重置为从 1 开始,其中 identity_columns.last_value 为 NULL

问题描述

DBCC在 100 多个表上运行命令以重置大多数表处于创建表后甚至没有插入单条记录的状态的标识值。

所以运行后

DBCC CHECKIDENT ('{tableName}', RESEED, 0)

在表上,它在所有新表中设置identity_columns.last_valuenull,由于当我插入新记录时,标识列从而0不是1.

我可以插入一条记录并删除它以解决问题,如何一次修复所有表。

这是返回所有表的 identity_columns.last_value查询null

SELECT
    tables.name As TableName,
    identity_columns.last_value
FROM  
    sys.tables tables 
JOIN 
    sys.identity_columns identity_columns ON tables.object_id = identity_columns.object_id
WHERE 
    identity_columns.last_value IS NULL

标签: sqlsql-server

解决方案


我无法测试它,但这样的事情必须有效......

SQL

declare tableName varchar(100)

declare cur cursor for  
SELECT  
  tables.name As TableName
FROM sys.tables tables 
  JOIN sys.identity_columns identity_columns 
    ON tables.object_id=identity_columns.object_id
WHERE identity_columns.last_value IS NULL

open cur
fetch next from cur into @tableName

while @@fetch_status = 0
begin
  DBCC CHECKIDENT (@tableName, RESEED, 1)
  fetch next from cur into @tableName 
end

close cur
deallocate cur

推荐阅读