Let's say that I have the following table:
ID|Read ------- 1|true 2|false 3|false 4|false
... and I need to read the smallest identifier that has [Read] == false; plus, update that i read it now.
So, if I run my stored procedure dbo.getMinID, it will return ID: 2 and update [Read] β true.
CREATE PROCEDURE [dbo].[getMinID] ( @QueryID INT OUTPUT ) BEGIN SELECT TOP 1 @QueryID = [ID] from Table UPDATE Table SET [Read] = 1 WHERE [ID] = @QueryID END
The problem is that I have ten (10) asynchronous threads executing dbo.getMinID at the same time, and I CANNOT select them SAME [ID] under any circumstances. I am concerned that the second thread ran between my SELECT and UPDATE statements, returning [ID]: 2 in both scenarios.
How can I guarantee that I do not select / update the same record twice, no matter how many threads act on the stored procedure? ALSO, keep in mind that the table CONSTANTLY added new rows, so I cannot lock the table!
source share