0

寻求帮助解决这个死锁问题......我有一个存储过程,它从多个进程中被频繁调用,但在一个小表上(行数低至数千)......偶尔,我在 proc 上陷入僵局。
Proc 的目的是返回下一个“符合处理条件”的行。不要将同一行返回给proc的两个同时调用是非常重要的......(这部分工作正常)......但我不明白为什么有时会出现死锁。

这是一个 SQL Azure 数据库

感谢帮助

CREATE PROCEDURE [dbo].[getScheduledAccounts_Monitor]
    -- Add the parameters for the stored procedure here
    @count int,
    @timeout int = 1200,
    @forcedAccountId uniqueidentifier = NULL
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

    DECLARE @batchId uniqueidentifier
    SELECT @batchId = NEWID()

    BEGIN TRAN

    -- Update rows
    UPDATE Schedule 
    WITH (ROWLOCK)
    SET 
        LastBatchId = @batchId, 
        LastStartedProcessingId = NEWID(), 
        LastStartedProcessingTime = GETUTCDATE(),
        LastCompletedProcessingId = ISNULL(LastCompletedProcessingId, NEWID()),
        LastCompletedProcessingTime = ISNULL(LastCompletedProcessingTime, GETUTCDATE())
    WHERE 
        ActivityType = 'Monitor' AND 
        IsActive = 1 AND
        AccountId IN (
            SELECT TOP (@count) AccountId 
            FROM Schedule 
            WHERE 
                (LastStartedProcessingId = LastCompletedProcessingId OR LastCompletedProcessingId IS NULL OR DATEDIFF(SECOND, LastStartedProcessingTime, GETUTCDATE()) > @timeout) AND 
                IsActive = 1 AND ActivityType = 'Monitor' AND
                (LastStartedProcessingTime IS NULL OR DATEDIFF(SECOND, LastStartedProcessingTime, GETUTCDATE()) > Frequency)
            ORDER BY (DATEDIFF(SECOND, LastStartedProcessingTime, GETUTCDATE()) - Frequency) DESC
        ) AND
        AccountId = ISNULL(@forcedAccountId, AccountID)

    -- Return the changed rows
    SELECT AccountId, LastStartedProcessingId, Frequency, LastProcessTime, LastConfigChangeTime, ActivityType
    FROM Schedule 
    WHERE LastBatchId = @batchId

    COMMIT TRAN
END
4

1 回答 1

1

您可以使用应用程序锁来确保单次执行。下面的文章适用于 SQL 2005,但我确信该解决方案也适用于较新的版本。

http://www.sqlteam.com/article/application-locks-or-mutexes-in-sql-server-2005

于 2012-12-28T23:06:51.477 回答