Handling contention in SQL2K5

At my current organization we run a huge number of batch processes, and many of these have to go through a rules engine.  Essentially, the rules engine grabs all of the stuff that needs to be processed, and informs other processes that it's working with that set of data.

The problem we needed to solve was how do you ensure only one instance of the rules engine grabs a specific record or set of records without explicit locking. Or, in the words of one of my developers, if two people reach for the same apple, how do you make sure you don't end up with two apples.

Here's a quick SQL solution that solves this, and ensures that no two processes can get the same set of records.

DECLARE @MyBatch UNIQUEIDENTIFIER
SET @MyBatch = NEWID()

UPDATE [tbl_Widgets]
 SET ValGUID = @MyBatch,
 WidgetValStatus = 'Processing'
 WHERE WidgetValStatus = 'NeedsToBeProcessed'

--Return our set of records to work with - defined by GUID.
--Will only return the records set above
SELECT WidgetGUID FROM [tbl_Widgets]
 WHERE WidgetValStatus = 'Processing'
 AND ValGUID = @MyBatch

Print | posted on Wednesday, August 12, 2009 11:10 AM

Comments on this post

No comments posted yet.

Your comment:

 (will show your gravatar)