I have inserted records into a SQL Server database table. The table had a primary key defined and the auto increment identity seed is set to “Yes”. This is done primarily because in SQL Azure, each table has to have a primary key and identity defined.
But since I have to delete some records from the table, the identity seed for those tables will be disturbed and the index column (which is auto-generated with an increment of 1) will get disturbed.
How can I reset the identity column after I deleted the records so that the column has sequence in ascending numerical order?
The identity column is not used as a foreign key anywhere in database.
Use this stored procedure:
Just revisiting my answer. I came across a weird behaviour in sql server 2008 r2 that you should be aware of.
The first select produces
0, Item 1
.The second one produces
1, Item 1
. If you execute the reset right after the table is created the next value is 0. Honestly, I am not surprised Microsoft cannot get this stuff right. I discovered it because I have a script file that populates reference tables that I sometimes run after I re-create tables and sometimes when the tables are already created.Although most answers are suggesting
RESEED
to0
, and while some see this as a flaw forTRUNCATED
tables, Microsoft has a solution that excludes theID
This will check the table and reset to the next
ID
. This has been available since MS SQL 2005 to current.https://msdn.microsoft.com/en-us/library/ms176057.aspx
For a complete DELETE rows and reset the IDENTITY count, I use this (SQL Server 2008 R2)
Although most answers are suggesting RESEED to 0, But many a times we need to just reseed to next Id available
This will check the table and reset to the next ID.
Its always better to use TRUNCATE when possible instead of deleting all records as it doesn't use log space also.
In case we need delete and need to reset the seed, always remember that if table was never populated and you used
DBCC CHECKIDENT('tablenem',RESEED,0)
then first record will get identity = 0 as stated on msdn documentationThis is a common question and the answer is always the same: don't do it. Identity values should be treated as arbitrary and, as such, there is no "correct" order.