Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset identity seed after deleting records in SQL Server

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.

like image 757
xorpower Avatar asked Feb 17 '14 08:02

xorpower


People also ask

Does delete Reset identity column?

Delete does not reset identity values. Let's see how the truncate command behaves with the identity values. First, execute the command in example 5 to delete all rows of a table.

How can I reset identity column in SQL Server?

Here, to reset the Identity column in SQL Server you can use DBCC CHECKIDENT method. Syntax : DBCC CHECKIDENT ('table_name', RESEED, new_value); Note : If we reset the existing records in the table and insert new records, then it will show an error.

How do you keep identity count after truncating table?

To retain the identity counter, use DELETE instead. If you are set upon truncating the table, you can manually look up the maximum ID before truncating, and then reseed the table using DBCC CHECKIDENT .


1 Answers

The DBCC CHECKIDENT management command is used to reset identity counter. The command syntax is:

DBCC CHECKIDENT (table_name [, { NORESEED | { RESEED [, new_reseed_value ]}}]) [ WITH NO_INFOMSGS ] 

Example:

DBCC CHECKIDENT ('[TestTable]', RESEED, 0); GO 

It was not supported in previous versions of the Azure SQL Database but is supported now.


Thanks to Solomon Rutzky the docs for the command are now fixed.

like image 97
Petr Abdulin Avatar answered Sep 20 '22 17:09

Petr Abdulin