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

表中的id是这样的:

99 100 101 1200 1201...

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


当前回答

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.

其他回答

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

([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.

我想明白了。它是:

 DBCC CHECKIDENT ('tablename', RESEED, newseed)

如果你正在使用MySQL,试试这个:

ALTER TABLE tablename AUTO_INCREMENT = 1

如果你只是想在SQL服务器中重置主键/序列,以一个你想要的序列开始,这里有一个解决方案-

IDs:

99 100 101 1200 1201...

删除id为>= 1200的行。(如果你有外键约束绑定到这些必须处理或删除,也能够删除这个,请小心。) 现在你要确保你知道MAX ID,以确保:

(SELECT MAX(your_column_name) FROM your_table) + 1;

(注:+1为最大值后开始ID序列)

重新启动你的序列:

execute ('alter sequence your_column_name restart with ' + @max_id);

(注:with后面必须有空格) 现在新的记录将以102作为ID开始。