Was a bit suprised today to discover that my auto-increment primary key still gets incremented when an insert statement errors, with the result that we have “missing” numbers in our table.
Is there any reason why SQL was designed this way? And is there any way to override this behaviour?
I am accessing through Linq-to-SQL.
this is by design to deal with concurrency and make it as fast as possible (what would happen if 3 inserts happens at the same time and 1 is rolled back..that would mess up everything)..when an inserts starts sql server determines the value of the identity..if a rollback happens those values are not reused..there is nothing you can really do unless you want to run DBCC CHECKIDENT after every rollback
If you need a query that will identify gaps, take a look at this How to return all the skipped identity values from a table in SQL Server
The next version of SQL Server will have
sequenceswhich might help you with some of this stuff, take a look here: A first look at sequences in SQL Server Denali