In one of our apps, we read in data from a file and expand it into several tables. If any part of the file is corrupt, we halt the read, and delete whatever data got inserted.
The issue, here, is that we have an auto-increment ID on one of the import tables, and when we remove a problem file, the ID continues from its post-import value, rather than its pre-import value.
In other words…
- ID starts at 50.
- Insert 100 records, max ID is now 150.
- Delete 100 records, max ID is still 150.
- Insert 50 records, ID is 200.
We’ve “lost” the range of 100 records. Is there an “auto decrement” equivalent to go with the auto increment?
Autonumbers shouldn’t be that meaningful to you. Their guarantee is they provide uniqueness nothing more. You can still reseed if you are using sql server
DBCC CHECKIDENT.From BOL:
The following example forces the current identity value in the Employee table in the AdventureWorks database to a value of 30.
I am not recommending this but just pointing it out.
DBCC CHECKIDENTcan throw an error if you try to reseed to a value that is already being used, in that case you’d have to have logic if you were relying upon such a task.I question the thought process of what makes these numbers so important? It sounds like you want one additional field called
LineNumberthat is incremented or decremented, etc. But even in this case you have to handle the rows that come after the deleted record. So if you have 50 rows and you delete row 25 you have to renumber anything greater then 25: