寻求有关SQL Server死锁问题的帮助

时间:2012-12-28 20:48:57

标签: sql sql-server deadlock database-deadlocks

寻求帮助解决这个死锁问题...我有一个存储过程,它在很多进程中被频繁调用,但是在一个小表上(行数量很少)...偶尔,我在处理器上遇到了僵局 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

1 个答案:

答案 0 :(得分:1)

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

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