I have a number of records in a table with a Status column and I want to select a single record where Status = Pending and in the same atomic query mark it as Status = InProcess. What's the best way to do that?
This is needed because multiple queries can be running at the same time trying to process these records and I don't want two threads to be picking up the same record to process.
The UPDATE command in SQL is used to modify or change the existing records in a table. If we want to update a particular value, we use the WHERE clause along with the UPDATE clause. If you do not use the WHERE clause, all the rows will be affected.
The UPDATE from SELECT query structure is the main technique for performing these updates. An UPDATE query is used to change an existing row or rows in the database. UPDATE queries can change all tables' rows, or we can limit the update statement affects for certain rows with the help of the WHERE clause.
You can use OUTPUT clause:
UPDATE [table]
SET Status = 'InProcess'
OUTPUT deleted.*
WHERE Status = 'Pending'
Here you can use inserted table name if you want to get row with new status or deleted when old.
Here is an article about Using tables as Queues.
With this table create table T (ID int identity, Status varchar(15))
Something like this should keep you safe from deadlocks.
;with cte as
(
select top 1 *
from T with (rowlock, readpast)
where Status = 'Pending'
order by ID
)
update cte
set Status = 'InProcess'
output inserted.ID, inserted.Status
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With