我从SQL Server数据库的一个表中删除了一些记录。

表中的id是这样的:

99 100 101 1200 1201...

我想删除后来的记录(ID >1200),然后我想重置自动增量,以便下一个自动生成的ID将是102。所以我的记录是顺序的,有办法做到这一点在SQL Server?


当前回答

我想添加这个答案是因为DBCC checkident -方法在对表使用模式时会产生问题。用这个来确定:

DECLARE @Table AS NVARCHAR(500) = 'myschema.mytable';
DBCC CHECKIDENT (@Table, RESEED, 0);

如果需要检查操作是否成功,请使用

SELECT IDENT_CURRENT(@Table);

在上面的例子中应该输出0。

其他回答

我知道这是一个老问题。然而,我正在为MySQL寻找类似的解决方案,这个问题出现了。

对于那些正在寻找MySQL解决方案的人,你需要运行这个查询:

// important!!! You cannot reset the counter to a value less than or equal to the value that is currently in use. For both InnoDB and MyISAM, if the value is less than or equal to the maximum value currently in the AUTO_INCREMENT column, the value is reset to the current maximum AUTO_INCREMENT column value plus one.
   
ALTER TABLE <your-table-name> AUTO_INCREMENT = 100

文档

重置数据库中的每个键,从最后一个最高键的最大值开始自动递增:

Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED, 0)'

Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED)'

基于已接受的答案,对于那些遇到类似问题的人,具有完整的模式限定:

([MyDataBase]。[MySchemaName]。[MyTable])……导致一个错误,您需要在该DB的上下文中

也就是说,下面的代码会抛出一个错误:

DBCC CHECKIDENT ([MyDataBase].[MySchemaName].[MyTable], RESEED, 0)

用单引号括起全限定表名:

DBCC CHECKIDENT ('[MyDataBase].[MySchemaName].[MyTable]', RESEED, 0)

You do not want to do this in general. Reseed can create data integrity problems. It is really only for use on development systems where you are wiping out all test data and starting over. It should not be used on a production system in case all related records have not been deleted (not every table that should be in a foreign key relationship is!). You can create a mess doing this and especially if you mean to do it on a regular basis after every delete. It is a bad idea to worry about gaps in you identity field values.

执行以下命令重新播种mytable,使其从1开始:

DBCC CHECKIDENT (mytable, RESEED, 0)

在联机书籍(BOL, SQL帮助)中阅读它。还要注意,你的记录不要高于你所设置的种子。