为所有不以“_”开头的表重置 AutoIncrement

Reset AutoIncrement for all tables not starting with "_"

我需要将数据库中 tables 的 AutoIncrement 字段重置为 1。我发现这可以针对单个 table 使用:

DBCC CHECKIDENT (mytable, RESEED, 0)

我如何 运行 为除 table 以外的所有 table 名称以“_”开头的人?

我正在使用下一个脚本来执行此操作。也许使用 cursor 的性能不是很好,但不会花费太多时间。

declare @TableName varchar(100)

declare cur_Cursor CURSOR STATIC
FOR 

  select  TABLE_NAME 
  from    information_schema.tables
  where   TABLE_TYPE = 'BASE TABLE'
    and   OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 1

OPEN  cur_Cursor
FETCH NEXT FROM cur_Cursor into @TableName
WHILE @@FETCH_STATUS = 0
BEGIN

  IF LEFT(@TableName, 1) != '_'
    DBCC CHECKIDENT(@TableName, RESEED, 0)

  FETCH NEXT FROM cur_Cursor into @TableName

END
CLOSE cur_Cursor
DEALLOCATE cur_Cursor

你可以这样试试:

SELECT 
    IDENT_SEED(TABLE_NAME) AS Seed,
    IDENT_INCR(TABLE_NAME) AS Increment,
    IDENT_CURRENT(TABLE_NAME) AS Current_Identity,
    TABLE_NAME,
    'DBCC CHECKIDENT(' + TABLE_NAME + ', RESEED, ' + CAST(IDENT_SEED(TABLE_NAME) AS VARCHAR(10)) + ')'
FROM 
    INFORMATION_SCHEMA.TABLES
WHERE 
    OBJECTPROPERTY(OBJECT_ID(TABLE_NAME), 'TableHasIdentity') = 1
    AND TABLE_TYPE = 'BASE TABLE'
    AND TABLE_NAME not like '_%'

这将为您提供所有 SQL 所需的查询:

Select 'DBCC CHECKIDENT '+quotename(OBJECT_NAME(OBJECT_ID))+', RESEED, 0); ' From sys.columns Where is_identity = 1
    and left(OBJECT_NAME(OBJECT_ID), 1) <> '_'

您可以 copy/paste 它并执行它,或者将它包装到游标中。