Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server identity column incrementing without insert

I have a C# console app which is using a stored procedure to insert rows into a SQL Server database. Currently the database has about 1m rows, however the ID column is up at 26m!

On the last successful insert the ID went from 16m to 26m. The app runs multiple threads in parallel so there is a chance it could be trying to insert two things at the same time.

Is there anything other than a transaction rollback that would cause the identity column to increment without adding a row?

It seems unlikely that there were 10 million times that two threads tried to write a conflicting row at the same time.

I'm using a temporary table variable which is populated by passing XML into the stored proc:

-- insert data if it doesn-t already exist  
insert into DataStore (DataText, DataSourceID)
select distinct td.dataText, td.dataSource 
  from @tempData td
 where not exists ( select 'x' 
                      from DataStore ds 
                     where ds.DataText = td.dataText );
like image 1000
finoutlook Avatar asked Jul 09 '26 18:07

finoutlook


2 Answers

What can leave gaps?

  • DELETEs
  • Explicit rollbacks
  • Constraint violations (= implied rollback)
  • SET IDENTITY_INSERT
  • Replication without NOT FOR REPLICATION clause
  • DBCC CHECKIDENT (edit: as per Oleg Dok's answer) ...

I'd also check the increment value using IDENT_INCR in case it is really is 5 million or such

like image 199
gbn Avatar answered Jul 12 '26 08:07

gbn


Inserted and deleted record increments identity counter, as mentioned by @gbn - Rollbacks and c-violations also, but there is two more options:

  • SET IDENTITY_INSERT
  • DBCC CHECKIDENT(..., RESEED)
like image 23
Oleg Dok Avatar answered Jul 12 '26 08:07

Oleg Dok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!