gpt4 book ai didi

sql - 使用 TABLOCK、XLOCK 命令在 Microsoft SQL Server 2008 上出现间歇性死锁

转载 作者:行者123 更新时间:2023-12-04 22:41:34 26 4
gpt4 key购买 nike

我遇到以下存储过程的间歇性死锁。它每分钟运行一次。它已经投入生产超过 1 年,我们通常不会收到此错误,但它有时会突然出现......在我们的一个环境中每天抛出 3 到 5 次异常......它与其他实例的环境相同没有抛出错误。存储过程被制作成一次只能运行一次,但也许我们这样做的方式不正确?

这里是错误:

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Data.SqlClient.SqlException: Transaction (Process ID 60) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.

存储过程如下:

 SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[requestUpdate]
AS
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

BEGIN TRAN
DECLARE @StartDate datetime,
@EndDate datetime,
@Throttle bit,
@Expired bit

SELECT @Throttle = 0
SELECT @Expired = 0

SELECT TOP 1 @StartDate = uq.StartDate, @EndDate = uq.EndDate
FROM UpdateQueue uq WITH(TABLOCK,XLOCK)
ORDER BY ID DESC

-- PREVENT ANOTHER REQUEST IF THIS SP HAS BEEN
-- CALLED IN THE LAST FORTY SECONDS.
IF DATEADD(SECOND,-40,GETDATE()) < @StartDate
BEGIN
SELECT @Throttle = 1
END

-- CREATE ANOTHER REQUEST IF THE CURRENT ONE
-- HAS NOT COMPLETED IN THE LAST FIVE MINUTES.
IF @StartDate <= DATEADD(MINUTE,-5,GETDATE())
BEGIN
SELECT @Expired = 1
END

-- HAS THE CURRENT REQUEST EXPIRED?
IF @EndDate IS NULL AND @Expired = 1
BEGIN
INSERT INTO UpdateQueue (RequestID, StartDate) OUTPUT 'EXPIRED' AS Result, INSERTED.RequestID AS RequestID
VALUES (NEWID(), GETDATE())
END

-- HAS THE CURRENT REQUEST COMPLETED AND YOU ARE NOT THROTTLING
-- OR HAVE THERE NOT BEEN ANY REQUESTS YET?
ELSE IF (@EndDate IS NOT NULL AND @Throttle = 0) OR @StartDate IS NULL
BEGIN
INSERT INTO UpdateQueue (RequestID, StartDate) OUTPUT 'STARTED' AS Result, INSERTED.RequestID AS RequestID
VALUES (NEWID(), GETDATE())
END

-- Running
ELSE
BEGIN
SELECT 'RUNNING' AS Result, NULL AS RequestID
END

COMMIT

最佳答案

我怀疑这是某个特定锁的持有时间超过了您的连接愿意等待的时间。如果没有什么可以终止长时间运行的事务,在这里,您将遇到这种情况,因为当连接超时时,SQL Server 会强制等待结束并终止作为死锁受害者的传入锁。

长话短说:一些进程(不是这里详述的)正在锁定表,导致死锁。

检查当您遇到死锁时还发生了什么 - 是否有备份正在运行,或者其他什么东西锁定了这个表?

关于sql - 使用 TABLOCK、XLOCK 命令在 Microsoft SQL Server 2008 上出现间歇性死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12900038/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com