Return unlocked rows in a “select top n” query

后端 未结 4 2053
再見小時候
再見小時候 2021-01-02 18:17

I need to have a MsSql database table and another 8 (identical) processes accessing the same table in parallel - making a select top n, processing those n rows, and updating

4条回答
  •  暖寄归人
    2021-01-02 18:51

    Here's a sample I blogged about a while ago:

    The READPAST hint is what ensures multiple processes don't block each other when polling for records to process. Plus, in this example I have a bit field to physically "lock" a record - could be a datetime if needed.

    DECLARE @NextId INTEGER
    BEGIN TRANSACTION
    
    -- Find next available item available
    SELECT TOP 1 @NextId = ID
    FROM QueueTable WITH (UPDLOCK, READPAST)
    WHERE IsBeingProcessed = 0
    ORDER BY ID ASC
    
    -- If found, flag it to prevent being picked up again
    IF (@NextId IS NOT NULL)
        BEGIN
            UPDATE QueueTable
            SET IsBeingProcessed = 1
            WHERE ID = @NextId
        END
    
    COMMIT TRANSACTION
    
    -- Now return the queue item, if we have one
    IF (@NextId IS NOT NULL)
        SELECT * FROM QueueTable WHERE ID = @NextId
    

提交回复
热议问题