Reputation: 527
i got a little problem in my SQL Query. The following error is :
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
And here is my SQL Query
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
I have already read from some articles over the Internet, and some of articles, tell me to tune up my query. But i don't know where's the error point or maybe deadlock point, and I don't know how to tune up my query code. Thanks :)
Upvotes: 0
Views: 9281
Reputation: 300827
Your stored procedure code conditionally starts a transaction, but commits if there was no error, rather than also checking if a transaction is in progress. See @@TRANCOUNT
.
The fact you are trying to use a named transaction suggests there are other transactions likely to be active. Unless you are a guru (and I'm not) I would strongly suggest not using named nested transactions. It is hard to get right and often leads to confusing, hard to maintain code.
Upvotes: 2