Question

I have a need for unique identifiers in my application. To that end, I created a table in my database that only contains 1 column 'unique_id" (BIGINT) and 1 row. The idea is to use a stored procedure to get the next identifier when I need it. I figured a 1-line operation like this would do the job:

UPDATE identifier_table SET unique_id = unique_id + 1 OUTPUT INSERTED.unique_id

Can someone confirm if this operation is atomic, or do I need to setup a lock on the table?

Thanks!

Was it helpful?

Solution

It is atomic. It is just a single update statement, and will have no problem at all with concurrency since that will be managed by the engine with update locks. You can use OUTPUT as shown, or you can do something like this:

DECLARE @unique_id bigint;

UPDATE identifier_table
SET
   @unique_id = unique_id + 1,
   unique_id = unique_id + 1;

SELECT @unique_id uniqueid;

If you make @unique_id an OUTPUT parameter, then you can get the value without a select statement or use it easily in another stored procedure.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top