【问题标题】:execute stored procedure atomicly原子地执行存储过程
【发布时间】: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


    【解决方案1】:

    您的事务(即“begin trans”和“commit”之间的语句)是原子的,即所有语句都将提交到数据库,或者都不提交。

    您的事务似乎与同步/互斥执行混合在一起。

    了解有助于强制执行顺序执行的事务隔离级别 - 可重复读取可能会起到作用。 http://en.wikipedia.org/wiki/Isolation_(database_systems)

    【讨论】:

    • 这似乎可行,但我遇到了一些异常,可能是死锁。我会调试一下并进一步弄清楚。
    • Failed to access Queue: Transaction (Process ID 60) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.这正常吗?
    • 好的,修改为serializable(来自repeatable read),现在看来不是死锁了,谢谢。
    猜你喜欢
    • 2010-09-20
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多