Tuesday, 4 October 2011

How To Reset an Identity Column in MSSQL / SQL Server

Something I often find myself needing to do is reset the identity column on auto incrementing field in MS SQL / SQL Server.

There are a couple of ways of doing it:
  1. If you are emptying the table, instead of using a DELETE, use a TRUNCATE. That will automatically reset the identity.
  2. The ID can be set to a specific number by using DBCC CHECKIDENT([TABLE_NAME], RESEED, n). Where n is the number that is to be set.
If you already have data in the table and you want to make sure that the sequence is followed, then use this:
DBCC CHECKIDENT([TABLE_NAME], RESEED, 0)
DBCC CHECKIDENT([TABLE_NAME], RESEED)

No comments:

Post a Comment