Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DBCC CHECKIDENT(myTable, RESEED,1) reseeding from 2

In SQL Server 2012, the following query is seeding the identity column myTable_id from 2 instead of 1. Why? myTable_id is also PK.

DELETE FROM myTable;
GO
SELECT * FROM myTable --0 rows are returned as expected
GO
DBCC CHECKIDENT(myTable, RESEED,1)
GO
INSERT INTO myTable(col1,col2,col3) SELECT FROM AnotherTable(col1,col2,col3)
GO
SELECT * FROM myTable --1005 rows are returned as expected, but identity value starts from 2
GO

Remark:

  1. The data inserted is right, the only issue is that the newly inserted data starts from 2 instead of 1.
  2. In the above sql code if I use DBCC CHECKIDENT(myTable, RESEED,0) the identity column correctly starts from 1.
  3. Following is snapshot in SSMS for the myTable_id column:

enter image description here

like image 332
nam Avatar asked Aug 10 '17 15:08

nam


Video Answer


2 Answers

From the docs:

The seed value is the value inserted into an identity column for the very first row loaded into the table. All subsequent rows contain the current identity value plus the increment value where current identity value is the last identity value generated for the table or view.

So if you seed from 10, the next value to be inserted will be 11.

like image 177
DavidG Avatar answered Oct 14 '22 16:10

DavidG


There is nothing bad with the answer here but the confusion comes from Microsoft approach itself.

I think that:

DBCC CHECKIDENT(myTable, RESEED, 0)

Should have the same behavior everywhere:

  1. on new created table,
  2. after delete table records,
  3. after truncating the table

Otherwise we need to check the table status before running this.

like image 31
gogosweb Avatar answered Oct 14 '22 16:10

gogosweb