I am planning to implement a kind-of work queue for users using only a SQL Server table. A row will be assigned to only one user at a time. I was planning to go a common UPDATE SET
.. WHERE
.. route, like has been proposed in this question:
https://stackoverflow.com/a/9241466
Here is the relevant part, quoted:
;WITH CTE AS
(
SELECT TOP 100 *
FROM T1
ORDER BY F2
)
UPDATE CTE SET F1='foo'
To ensure only one user actually gets to edit a row, I will include an additional property, UserId, and check for NULL
in a WHERE
clause.
;WITH CTE AS
(
SELECT TOP 5 *
FROM T1
WHERE UserId IS NULL
ORDER BY F2
)
UPDATE CTE SET UserId = @userid
After statement completion, I will SELECT
the affected rows from the database.
However, I might want to include some additional properties in my WHERE
clause, and also some additional ordering.
UPDATE
will lock the row if the WHERE
is included, but is this still the case for when the WHERE
is included in the CTE
?
My question is, differently phrased, will UPDATE
still lock the rows or is there a chance that two concurrently run statements will overwrite the UserId because of a racing issue?