Reset AutoIncrement in SQL Server after Delete

2019-01-01 14:31发布

I've deleted some records from a table in a SQL Server database. Now the ID's go from 101 to 1200. I want to delete the records again, but I want the ID's to go back to 102. Is there a way to do this in SQL Server?

10条回答
只靠听说
2楼-- · 2019-01-01 14:36

Try this:

ALTER TABLE tablename AUTO_INCREMENT = 1
查看更多
十年一品温如言
3楼-- · 2019-01-01 14:36

I figured it out. It's:

 DBCC CHECKIDENT ('tablename', RESEED, newseed)
查看更多
倾城一夜雪
4楼-- · 2019-01-01 14:38
DBCC CHECKIDENT('databasename.dbo.tablename', RESEED, number)

if number=0 then in the next insert the auto increment field will contain value 1

if number=101 then in the next insert the auto increment field will contain value 102


Some additional info... May be useful to you

Before giving auto increment number in above query, you have to make sure your existing table's auto increment column contain values less that number.

To get the maximum value of a column(column_name) from a table(table1), you can use following query

 SELECT MAX(column_name) FROM table1
查看更多
只若初见
5楼-- · 2019-01-01 14:39

Based on the accepted answer, for those who encountered a similar issue, with full schema qualification:

([MyDataBase].[MySchemaName].[MyTable])... results in an error, you need to be in the context of that DB

That is, the following will throw an error:

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

Enclose the fully-qualified table name with single quotes instead:

DBCC CHECKIDENT ('[MyDataBase].[MySchemaName].[MyTable]', RESEED, 0)
查看更多
爱死公子算了
6楼-- · 2019-01-01 14:42

Delete and Reseed all the tables in a database.

    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.
查看更多
几人难应
7楼-- · 2019-01-01 14:47

Issue the following command to reseed mytable to start at 1:

DBCC CHECKIDENT (mytable, RESEED, 0)

Read about it in the Books on Line (BOL, SQL help). Also be careful that you don't have records higher than the seed you are setting.

查看更多
登录 后发表回答