3

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 );
4
  • 1
    You have a race condition there. That pattern will not work under concurrency as illustrated here Commented Dec 28, 2011 at 11:37
  • Does DataText have a unique constraint on it? Maybe you did actually encounter a whole load of rollbacks. Commented Dec 28, 2011 at 11:44
  • DataText doesn't have a constraint, but another column DateCreated (populated by default value of getdate()) does have one. Commented Dec 28, 2011 at 12:59
  • (but DateCreated isn't a unique constraint I forgot to mention) Commented Dec 28, 2011 at 14:11

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Increment is 1, never doing any deletes on the table. I'll take a look at constraints.
@finoutlook: added more ideas
2

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)

1 Comment

I added DBCC CHECKIDENT to my answer, forgot about that one. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.