我在SQL查询中遇到了一些问题。以下错误是:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
这是我的SQL查询
ALTER PROC sp_savepresence
@Username char(20),
@Image text
AS
BEGIN
------------
DECLARE @PresStatus CHAR,
@DateDiff INT,
@ClockIn DATETIME,
@InsertData varchar(20) = 'TranSavePresence';
IF NOT EXISTS(SELECT Username FROM PresenceTransaction WHERE Username=@Username AND ClockOut IS NULL)
BEGIN
BEGIN TRANSACTION @InsertData
INSERT INTO PresenceTransaction
(
Username,
[Image],
PresenceStatus,
WorkHour,
ClockIn,
ClockOut
)
VALUES
(
@Username,
@Image,
'N',
0,
getdate(),
NULL
)
END
ELSE
BEGIN
SELECT @ClockIn = ClockIn, @DateDiff = DateDiff(MINUTE, @ClockIn, getDate()) FROM PresenceTransaction WHERE Username=@Username AND ClockOut IS NULL AND PresenceStatus = 'N'
IF @DateDiff IS NOT NULL
BEGIN
SELECT @PresStatus = 'P'
END
ELSE
BEGIN
SELECT @PresStatus='N'
END
UPDATE PresenceTransaction
SET
PresenceStatus = @PresStatus,
WorkHour = @DateDiff,
ClockOut = getDate()
WHERE Username=@Username AND ClockOut IS NULL AND PresenceStatus = 'N'
END
------------
IF(@@Error <> 0)
BEGIN
PRINT @@Error
Rollback Tran @InsertData
SELECT @@Error AS [Status]
END
ELSE
BEGIN
COMMIT TRAN @InsertData
SELECT 'True' AS [Status]
END
END
GO
我已经从互联网上的一些文章中读过,有些文章告诉我要调整我的查询。但我不知道错误点或死锁点在哪里,我不知道如何调整我的查询代码。谢谢:))
答案 0 :(得分:2)
您的存储过程代码有条件地启动事务,但是如果没有错误则提交,而不是检查事务是否正在进行中。请参阅@@TRANCOUNT
。
您尝试使用命名事务的事实表明还有其他事务可能处于活动状态。除非你是一个大师(而我不是),否则我强烈建议不要使用命名的嵌套事务。很难做到正确并经常导致令人困惑,难以维护的代码。