【发布时间】:2014-09-25 05:27:33
【问题描述】:
我在 sql 中创建了一个“队列”,我希望能够将一个项目设置为不可见以半模拟一个类似天蓝色的队列(而不是在工作人员无法处理它时立即删除它,它将再次自动出现在队列中以供其他工作人员获取)。
根据此 SO 的建议:Is T-SQL Stored Procedure Execution 'atomic'?
我将 Begin Tran 和 Commit 包裹在我的 spDeQueue 过程中,但我仍然遇到来自我的测试代理的重复拉取。 (他们都试图同时清空 10 个队列,而我得到重复读取,这是我不应该的)
这是我的存储过程
ALTER PROCEDURE [dbo].[spDeQueue]
@invisibleDuration int = 30,
@priority int = null
AS
BEGIN
begin tran
declare @now datetime = GETDATE()
-- get the queue item
declare @id int =
(
select top 1
[Id]
from
[Queue]
where
([InvisibleUntil] is NULL or [InvisibleUntil] <= @now)
and (@priority is NULL or [Priority] = @priority)
order by
[Priority],
[Created]
)
-- set the invisible and viewed count
update
[Queue]
set
[InvisibleUntil] = DATEADD(second, @invisibleDuration, @now),
[Viewed] = [Viewed] + 1
where
[Id] = @id
-- fetch the entire item
select
*
from
[Queue]
where
[Id] = @id
commit
return 0
END
我应该怎么做才能确保它以原子方式运行,以防止重复出队。
谢谢
【问题讨论】:
标签: sql-server stored-procedures concurrency queue atomic