我从SQL Server数据库的一个表中删除了一些记录。
表中的id是这样的:
99 100 101 1200 1201...
我想删除后来的记录(ID >1200),然后我想重置自动增量,以便下一个自动生成的ID将是102。所以我的记录是顺序的,有办法做到这一点在SQL Server?
我从SQL Server数据库的一个表中删除了一些记录。
表中的id是这样的:
99 100 101 1200 1201...
我想删除后来的记录(ID >1200),然后我想重置自动增量,以便下一个自动生成的ID将是102。所以我的记录是顺序的,有办法做到这一点在SQL Server?
当前回答
DBCC CHECKIDENT('databasename.dbo.tablename', RESEED, number)
如果number = 0,那么在下一次插入时,自动递增字段将包含值1
如果number = 101,那么在下一次插入时,自动递增字段将包含值102
一些额外的信息…可能对你有用 在上述查询中给出自动递增数之前,必须确保现有表的自动递增列包含的值小于该数。
要从表(table1)中获取列(column_name)的最大值,可以使用以下查询
SELECT MAX(column_name) FROM table1
其他回答
我知道这是一个老问题。然而,我正在为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
文档
半保证没有白痴:
declare @max int;
select @max = max(key) from table;
dbcc checkident(table,reseed,@max)
http://sqlserverplanet.com/tsql/using-dbcc-checkident-to-reseed-a-table-after-delete
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)
删除数据库中的所有表并重新播种。
USE [DatabaseName]
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all" -- Disable All the constraints
EXEC sp_MSForEachTable "DELETE FROM ?" -- Delete All the Table data
Exec sp_MSforeachtable 'DBCC CHECKIDENT(''?'', RESEED, 0)' -- Reseed All the table to 0
Exec sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all" -- Enable All the constraints back
-- You may ignore the errors that shows the table without Auto increment field.