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.
UNIQUEIDENTIFIER(UUID) instead ofINTEGER. In this case you can basically create it on the client side, pass it to theSQLand do not have to worry about it. The disadvantage is that, of course, the size of this field.CREATE TABLE ID_GEN (ID INTEGER IDENTITY), and use this as afactoryto give you the identifiers. Ideally you would create a stored procedure (or function), to which you would pass the number of identifiers you need. The stored procedure will then insert this number of rows (empty) into thisID_GENtable and will return you all newID‘s, which you can use in your code. Obviously, your original tables will not have theIDENTITYanymore.ID_Factoryabove.I would choose simplicity (
UUID) if you are not constrained otherwise.