How to properly reserve identity values for usage in a database?

Posted by esac on Stack Overflow See other posts from Stack Overflow or by esac
Published on 2010-06-16T19:46:26Z Indexed on 2010/06/16 20:12 UTC
Read the original article Hit count: 230

We have some code in which we need to maintain our own identity (PK) column in SQL. We have a table in which we bulk insert data, but we add data to related tables before the bulk insert is done, thus we can not use an IDENTITY column and find out the value up front.

The current code is selecting the MAX value of the field and incrementing it by 1. Although there is a highly unlikely chance that two instances of our application will be running at the same time, it is still not thread-safe (not to mention that it goes to the database everytime).

I am using the ADO.net entity model. How would I go about 'reserving' a range of id's to use, and when that range runs out, grab a new block to use, and guarantee that the same range will not be used.

© Stack Overflow or respective owner

Related posts about c#

Related posts about sql