Click here to Skip to main content
15,887,464 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I wrote a below stored proc to retrieve work items from database table which is acting as a queue. There are five threads running which is polling table called ReqResp for work to be done and once it picks the work it can update the response back to that record. I have a primary key called SSID on that table and a flag IsProcessedByWorker to indicate if work is picked by worker or not.

Will below stored proc be sufficient to make sure work item can be picked by only one worker ?


SQL
ALTER PROCEDURE [dbo].[SelectWorkItem]
	@Worker varchar(25),
	@PickedTime datetime,
	@SSID varchar(200) OUTPUT
AS
BEGIN
BEGIN TRANSACTION;

WITH    q AS
        (
        SELECT  TOP 1 *
        FROM    ReqResp
        WHERE   IsProcessedByWorker = 0
        ORDER BY RequestIn 
        )
UPDATE  q
SET IsProcessedByWorker=1,PickedByWorkerNo=@Worker,RequestPicked=@PickedTime,@SSID=SSID

COMMIT TRANSACTION;

END
Posted
Updated 15-Mar-15 13:48pm
v2
Comments
barneyman 15-Mar-15 20:32pm    
i use the same form of query to achieve the same sort of thing (build nodes for a build system)

the only difference is i use an UPDLOCK in the update - http://www.sqlnotes.info/2012/10/10/update-with-updlock/
Subramanyam Shankar 16-Mar-15 8:16am    
Hi,

When using multiple threads you need to be careful about the race conditions and the locks. if your table is locked then they are chances of transaction failures.So you should be able to handle those as well.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900