Wednesday, November 23, 2011

Resetting a table's identity in SQL Server

The following syntax is what's needed if at any time you need to reset the auto-identity (INT) of any table.

DBCC CHECKIDENT([tablename(string)], [command], [numbertoreseedto(int)])

So, for example, if I wanted to reset the current identity value for my Customer table to 39, I would write the following:

DBCC CHECKIDENT('Customer', RESEED, 39)

Note that the table name is in quotes. Also, it's important to note that the number you use for your reseed will increment by one for the next new entry into the table. Generally speaking you will be reseeding to the last known identity value in your table. So, in my example above, if the last row entry reads 39 as its ID column, then I will reseed to 39, meaning the next row I add will have an ID value of 40. I can reseed to 40 if I choose (actually you can in theory reseed to anything equal to or beyond the maximum ID value in the table currently), but it would mean that you'd end up with a 'gap' in your column IDs; so they might read: 39, 41, 42... and so on, with 40 being missing because of the way the RESEED occurred. So, assuming you're aiming for consecutive numbers (which most of us are when it comes to IDs for table rows) then always reseed to the last known identity value.

No comments:

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Fixes to common .NET problems, as well as information on .NET features and solutions to common problems that are not language-specific.

Z