Reset autoincrement in Microsoft SQL Server 2008 R2
Asked Answered
F

2

35

I created a primary key to be autoincrement.

  • I added two rows: ID=1, ID=2
  • I deleted these two rows.
  • I added a new row, but the new row's ID was: ID=3

How can I reset or restart the autoincrement to 1?

Farmyard answered 13/12, 2012 at 10:40 Comment(0)
S
63

If you use the DBCC CHECKIDENT command:

 DBCC CHECKIDENT ("YourTableNameHere", RESEED, 1);

But use with CAUTION! - this will just reset the IDENTITY to 1 - so your next inserts will get values 1, then 2, and then 3 --> and you'll have a clash with your pre-existing value of 3 here!

IDENTITY just dishes out numbers in consecutive order - it does NOT in any way make sure there are no conflicts! If you already have values - do not reseed back to a lower value!

Sconce answered 13/12, 2012 at 10:43 Comment(3)
I forgot to tell, I'm using Management Studio, so I want to reseed it with the Management StudioFarmyard
@victorio: just open a new query window and execute this T-SQL command!Sconce
I am using SQL server 2008 and to reset to value 1 I have to put 0 on the last parameter, then: DBCC CHECKIDENT ("YourTableNameHere", RESEED, 0);Emmanuelemmeline
E
21

I'm using SQL Server 2012 and the DBCC CHECKIDENT ("YourTableNameHere", RESEED, 1) causes a value of 2 on the very next insert.

So for SQL Server 2012, change the 1 to 0 to get a value of 1 for your next record insert:

DBCC CHECKIDENT ("YourTableNameHere", RESEED, 0);  -- value will be 1 for the next record insert
Eastlake answered 4/4, 2014 at 23:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.