Click here to Skip to main content
15,888,106 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a SQL database that has an Id field that has gone haywire. It has jumped from 688 to 1687 and continued from there. I can't figure out why the jump. How can I move through the database and change the Id number to match the record number and reset the count for the next Id number? Any help will be greatly appreciated.
Posted

If it's auto incrementing - i.e. it assigns a new value itself when you INSERT a value, then it's an IDENTITY field, and that behaviour is by design: when you remove existing rows, the ID numbers are not reused so you get gaps.
I wouldn't change it - the ID number isn't supposed to change, it's supposed to be a "permanent" unique value which identifies the row. If you want a value which is always in strict sequence, then use the ROWNUMBER function with your select to generate it on the fly instead of altering the ID value.

If you must change it, then the safest way is to create a new table with a non-identity ID value, and copy each row over, renumbering the ID's as you go. At the end, delete the old table and rename the new.
But if you use any foreign key values, you will likely cause enormous problems for yourself (and you'll probably have holes again in a month or two...)
 
Share this answer
 
Are you using SQL 2012 or higher? If so, this bug report[^] might be relevant. It refers to "failover", but the problem seems to affect non-clustered instances as well.


In SQL Server 2012 the implementation of the identity property has been changed to accommodate investments into other features. In previous versions of SQL Server the tracking of identity generation relied on transaction log records for each identity value generated. In SQL Server 2012 we generate identity values in batches and log only the max value of the batch. This reduces the amount and frequency of information written to the transaction log improving insert scalability.


The solution from Microsoft is to add trace flag 272 to the SQL Server startup options. This will cause SQL to use the same identity generation semantics as previous versions. However, it may have a negative impact on the identity generation performance.

Alternatively, you can replace specific identity columns with a sequence created with the NO CACHE option.

Database Engine Service Startup Options[^]
CREATE SEQUENCE (Transact-SQL)[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900