Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 My query is causing deadlock

Author  Topic 

vijays3
Constraint Violating Yak Guru

354 Posts

Posted - 2014-01-24 : 08:40:33
Hi All,

My below query is causing deadlock .is there any other way to rewrite it .


SELECT SumBal.Userid, SumBal.UserTransnumber,SumBal.moduleid, SumBal.clientid ,
SumBal.ChangeAmount , bl.FinalBalance, bl.SessionID, bl.[Time], bl.EventID, bl.RowID
FROM ( SELECT Userid, UserTransnumber,Moduleid, Clientid ,SUM(ChangeAmt) ChangeAmount
FROM tb_BalanceLog
WHERE UserID = @UserID AND RowID BETWEEN @MinRowID AND @MaxRowID
GROUP BY Userid, UserTransnumber,Moduleid, Clientid
) SumBal
JOIN tb_BalanceLog bl
ON SumBal.Userid = bl.UserID
AND SumBal.UserTransnumber = bl.UserTransNumber
JOIN (
SELECT UserID, UserTransnumber,MAX(rowid) RowID
FROM tb_Balancelog
WHERE userid = @UserID AND RowID BETWEEN @MinRowID AND @MaxRowID
GROUP BY UserID, UserTransnumber
) BalRow
ON bl.UserID = BalRow.UserID AND bl.RowID = BalRow.RowID


Vijay is here to learn something from you guys.

sqlsaga
Yak Posting Veteran

93 Posts

Posted - 2014-01-24 : 11:40:09
Basically I rewrote this using CTE's. It would be great if you can provide DDL and sample DML and the output so I can give the optimal result.

;WITH SumBal AS
(SELECT Userid, UserTransnumber,Moduleid, Clientid ,SUM(ChangeAmt) ChangeAmount
FROM tb_BalanceLog
WHERE UserID = @UserID AND RowID BETWEEN @MinRowID AND @MaxRowID
GROUP BY Userid, UserTransnumber,Moduleid, Clientid )
, BalRow AS
(SELECT UserID, UserTransnumber,MAX(rowid) RowID
FROM tb_Balancelog
WHERE userid = @UserID AND RowID BETWEEN @MinRowID AND @MaxRowID
GROUP BY UserID, UserTransnumber)
SELECT SumBal.Userid, SumBal.UserTransnumber,SumBal.moduleid, SumBal.clientid ,
SumBal.ChangeAmount , bl.FinalBalance, bl.SessionID, bl.[Time], bl.EventID, bl.RowID
FROM SumBal
INNER JOIN tb_BalanceLog bl ON SumBal.Userid = bl.UserID AND SumBal.UserTransnumber = bl.UserTransNumber
INNER JOIN balrow ON bl.UserID = BalRow.UserID AND bl.RowID = BalRow.RowID



Visit www.sqlsaga.com for more t-sql snippets and BI related how to's.
Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2014-01-24 : 12:16:57
You really need to look at both parts of the deadlock. There is a statement that is the deadlock victim and the statement that was allowed to complete.

You should probably read these to determine how to find and eliminate the deadlocks:
http://msdn.microsoft.com/en-us/library/ms178104.aspx
http://msdn.microsoft.com/en-us/library/ms188246.aspx





CODO ERGO SUM
Go to Top of Page
   

- Advertisement -