Using SQL Server as a DB queue with multiple clients

前端 未结 7 974
生来不讨喜
生来不讨喜 2020-12-04 08:06

Given a table that is acting as a queue, how can I best configure the table/queries so that multiple clients process from the queue concurrently?

For example, the ta

7条回答
  •  [愿得一人]
    2020-12-04 08:52

    One way is to mark the row with a single update statement. If you read the status in the where clause and change it in the set clause, no other process can come in between, because the row will be locked. For example:

    declare @pickup_id int
    set @pickup_id = 1
    
    set rowcount 1
    
    update  YourTable
    set     status = 'picked up'
    ,       @pickup_id = id
    where   status = 'new'
    
    set rowcount 0
    
    return @pickup_id
    

    This uses rowcount to update one row at most. If no row was found, @pickup_id will be -1.

提交回复
热议问题