How do I Optimization sql Query and replace CURSOR - sql

How would I Optimize this code removing the cursor
BEGIN TRANSACTION;
BEGIN
if exists (select AgreementNo from PFAgreements where Approved = 1 and finalized = 1 )
begin
if #Agreements <> 'ALL'
BEGIN
SELECT #CursorState = CURSOR_STATUS('global','curAgreement1')
if #CursorState = 1
--The cursor allocated to this variable is open.
--For insensitive and keyset cursors, the result set has at least one row.
--For dynamic cursors, the result set can have zero, one, or more rows
begin
CLOSE curAgreement1
DEALLOCATE curAgreement1
end
else if #CursorState = 0
--The cursor allocated to this variable is open, but the result set is definitely empty.*
begin
CLOSE curAgreement1
DEALLOCATE curAgreement1
end
else if #CursorState = -1
--The cursor allocated to this variable is closed.
begin
DEALLOCATE curAgreement1
end
declare curAgreement1 cursor for
(Select AgreementNo from PFAgreements where Approved = 1 and finalized = 1 AND AgreementNo = #Agreements)
END
ELSE
BEGIN
declare curAgreement1 cursor for
(Select AgreementNo from PFAgreements where Approved = 1 and finalized = 1)
END
open curAgreement1
Fetch next from curAgreement1 into #AgreementAno
while (##fetch_status = 0)
begin
SELECT
#Cno = ISNULL(BaseNo, ''),
#StartDate = CommencementDate,
#MaturityDate = MaturityDate,
#FirstInstalDate = FirstInstallmentDate,
#Tranch = ISNULL(Tranche, 0),
#MyCurrency = ISNULL(Currency, ''),
#Term = ISNULL(NoOfRepayments, 0),
#ApprovedAmount = ISNULL(LoanAppliedAmount , 0),
--#ApprovedAmount = ISNULL(LoanAppliedAmount - deposit , 0),
#IntRate = ISNULL(IntRate, 0),
#Registered = 0,
#RegisteredCollateral = '',
#DisbursementDate = ActivationDate,
#ProdCode = Product,
#CurOfRepayment = CurrencyRepayment
FROM dbo.PFAgreements
WHERE AgreementNo = #AgreementAno
--call saveupdate transitems
--ensures there is no accrual that hasent been paid up in transbill
exec uspsaveupdatetransitems #AgreementAno , #LogIP , #LogUser , #Compname
select #myrate = (select top 1 EXCHRATE from EXCHRATES where Company = #Company and CURRENCYDATE <= #ProcDate and CURRENCYCODE =#MyCurrency order by CURRENCYDATE desc)
select ISNULL(#MyRate , 1)
set #Rental = 0
set #rental = (Select top 1 rental from schedules where AgreementNo = #AgreementAno ORDER BY ID desc)
set #rental = isnull(#rental,0)
If exists(select DateDue from Schedules where agreementno = #AgreementAno)
begin
Set #maturityDate = (Select Max(DateDue) From schedules where AgreementNo = #AgreementAno)
end
set #Names =( Select dbo.GetCustomerNamePF (#AgreementAno))
--deallocate rowcount
set #rowcount =0
set #rowcount = (Select count(AgreementNo) from PFAgreements Where AgreementNo=#AgreementAno and Finalized = 1 and Approved = 1 )
if #rowcount>0
begin
declare #TxRow int
set #TxRow =#rowcount - 1
Declare #TotalInt as numeric(18,2)
select #TotalInt = isnull((Select case when Sum(AmountDue) is null then 0 else Sum(AmountDue) end Amount from Schedules where AgreementNo = #AgreementAno and ItemCode = '11' and Processed = 0 ),0)
--Tom 2017-04-18: Check if there is Written Off or Terminated Interest
select #TerminatedInt = isnull((select UFCBal from IPFTerminatedAgreements where AgreementNo = #AgreementAno ),0)
select #WritenOffInt = isnull((select isnull(sum((AmountDue-AmountPaid)),0) from WriteOffDetails where ContractNo = #AgreementAno and REJECTED=0),0)
--Therefore the Interest Balance
select #TotalInt = #TotalInt - #TerminatedInt - #WritenOffInt
--End of Tom
if #TotalInt < 0
begin
select #TotalInt = 0
end
select #LastCreditDate = ISNULL(dbo.LastCreditDate(#AgreementAno),'1900-01-01'), #NoOFArr = dbo.NoOfArrsModif(#AgreementAno,#ProcDate) ,
#NoOfArrReal = dbo.NoOfArrs(#AgreementAno,#ProcDate) , #nextduedate = isnull(dbo.FirstAccrualDate(#AgreementAno),dbo.FirstAccrualDatePaid(#AgreementAno)) ,
#PrincipalBal = dbo.GetPrinBalBFPF(#AgreementAno,#ProcDate) ,#PrincipalBalBccy = #PrincipalBal * #MyRate ,
--#InterestBal =#TotalInt + ( Select case when Sum(AmountDue) is null then 0 else Sum(AmountDue) end Amount from Trans_Bill where AgreementNo = #AgreementAno and ItemCode = '11' and ReAccrual = 0 ),
#InterestBal =#TotalInt ,
--kenwillis 12042016
--commented line shows initial interest. above new shows interest to maturity un processesd
#InterestBalBccy = ( #InterestBal * #MyRate ) ,
#TrustBal = (Select case when Sum(AmountFcy) IS null then 0 else Sum(AmountFcy) end Amount from ReceiptOverPayments where AgreementNo = #AgreementAno ) ,
#TrustBalBccy = (#TrustBal * #myrate) ,
#OtherBal = (select case when Sum(Amountdue - AmountPaid) IS null then 0 else Sum(Amountdue - AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno
and DateDue < = #procdate and ItemCode in(Select chargesCode from charges) and AmountDue > 0 ) ,
#OtherBalBccy = #OtherBal * #myrate ,
#PrincipalArrears = dbo.GetPrinArrBF(#AgreementAno , #ProcDate ) , #PrincipalArrearsBccy = #PrincipalArrears * #MyRate ,
#InterestArrears = (Select case when Sum(AmountDue-AmountPaid) is null then 0 else Sum(AmountDue-AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno and DateDue < = #ProcDate
and ItemCode = '11' and Item not like '%default%' and (ReAccrual = 0 or ReAccrual = 1) ) ,
#InterestArrearsBccy = ( #InterestArrears * #MyRate ) ,
#OtherArrears = (Select case when Sum(AmountDue-AmountPaid) is null then 0 else Sum(AmountDue-AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno and DateDue < = #procdate and ItemCode NOT in('10','11','19') and AmountDue > 0 ),
#OtherArrearsBccy = #OtherArrears * #myrate ,
#ArrearsInterest = ( Select case when Sum(AmountDue-AmountPaid) is null then 0 else Sum(AmountDue-AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno and DateDue < = #procdate and ItemCode = '11' and
Item like '%Default%' ) ,
#ArrearsInterestBccy = #ArrearsInterest * #MyRate ,
#PrinArrearsNotdue = 0 , #PrinArrearsNotdueBccy = 0 , #MoOut = 0,
#DaysInArr = dbo.NoOfArrs(#AgreementAno,#ProcDate),
#chargesSp = (Select case when Sum(AmountDue-AmountPaid) is null then 0 else Sum(AmountDue-AmountPaid) end Amount from Trans_Bill where AgreementNo = #AgreementAno and DateDue < = #procdate and ItemCode in(Select chargesCode from charges where affectsincome = 0) and AmountDue > 0 )
select #nextduedate = isnull(#nextduedate,(select TOP 1 datedue from schedules where agreementno = #AgreementAno and processed = 0 ))
select #BaldateRep = #nextduedate
if #InterestArrears < 0
begin
select #InterestArrears = 0
select #InterestArrearsBccy = #InterestArrears * #MyRate
end
end
else
begin
-- select #PrincipalBal = #ApprovedAmount, #PrincipalBalBccy = #ApprovedAmount , #InterestBal = 0 ,
-- #TrustBal = 0 , #TrustBalBccy = 0 , #OtherBal = 0 , #OtherBalBccy = 0 , #PrincipalArrears = 0 ,
-- #PrincipalArrearsBccy = 0 , #InterestArrears = 0 , #InterestArrearsBccy = 0 , #OtherArrears = 0 ,
-- #OtherArrearsBccy = 0 , #ArrearsInterest = 0 , #ArrearsInterestBccy = 0 , #MoOut = 0 ,
-- #PrinArrearsNotdue = 0 , #PrinArrearsNotdueBccy = 0 , #LastCreditDate = '1900-01-01' , #NoOFArr = 0 ,
-- #NoOfArrReal = 0 , #BaldateRep = '1900-01-01' , #DaysInArr = 0
-- end
-- INSERT INTO LhTransBalancePF
-- (
-- BalDate, Currency, ExchangeRate, BaseNo, AgreementNo, Names, PostDate, Tranche , StartDate ,
-- FirstInstaldate , MaturityDate, Term, ApprovedAmount , PaymentFrequency , Rental ,
-- LastPaymentDate , NoOfArrears, ProdCode, ProdName , DaysInArrears, PrincipalBal ,
-- PrincipalBalBccy , InterestBal, InterestBalBccy , TrustBal , TrustBalBccy, OtherBal, OtherBalBccy ,
-- PrincipalArrears , PrincipalArrearsBccy , InterestArrears , InterestArrearsBccy , OtherArrears ,
-- OtherArrearsBccy, ArrearsInterest, ArrearsInterestBccy, MoOutstanding, PostingUser,LastAccrualdate ,
-- IntRate,PricipalArrearsNotDue,PrincipalArrNotDueBccy,NoOfArrearsReal
-- )
-- VALUES
-- (
-- ISNULL(#BalDate,'1900-01-01') ,ISNULL(#MyCurrency,'') ,ISNULL(#MyRate,1) ,ISNULL(#Cno,'') , ISNULL(#AgreementAno,'') ,ISNULL(#Names,'') , ISNULL(#Baldate,'1900-01-01') , ISNULL(#Tranch,0) , ISNULL(#StartDate,'1900-01-01') ,
-- ISNULL(#FirstInstaldate,'1900-01-01') , ISNULL(#MaturityDate,'1900-01-01') , ISNULL(#Term,0) , ISNULL(#ApprovedAmount,0) ,3 ,iif(#Rental=null,0,#Rental) ,
-- #LastCreditDate , ISNULL(#NoOFArr,0) , '' , '' , ISNULL(#DaysInArr,0) , ISNULL(#PrincipalBal,0) ,
-- ISNULL(#PrincipalBalBccy,0) , ISNULL(#InterestBal,0) , ISNULL(#InterestBalBccy,0) , ISNULL(#TrustBal,0) ,ISNULL(#TrustBalBccy,0) ,ISNULL(#OtherBal,0), ISNULL(#OtherBalBccy,0) ,
-- ISNULL(#PrincipalArrears,0) , ISNULL(#PrincipalArrearsBccy,0) , ISNULL(#InterestArrears,0) , ISNULL(#InterestArrearsBccy,0) , ISNULL(#OtherArrears,0) ,
-- ISNULL(#OtherArrearsBccy,0) , ISNULL(#ArrearsInterest,0) , ISNULL(#ArrearsInterestBccy,0) , ISNULL(#MoOut,0) , 'SYSTEM',ISNULL(#BaldateRep,'1900-01-01') ,
-- ISNULL(#intRate,0),ISNULL(#PrinArrearsNotdue,0) ,ISNULL(#PrinArrearsNotdueBccy,0) ,ISNULL( #NoOfArrReal ,0)
-- )
--update LHTransBalancePF set Registered = #Registered, RegisteredCollateral = #RegisteredCollateral,
--ProdCode = #ProdCode ,loansizecategory = case when ApprovedAmount < = 5000000 then 'SMALL'
--WHEN ApprovedAmount > 5000000 and ApprovedAmount < = 30000000 then 'MEDIUM'
--ELSE 'LARGE' END
--WHERE AgreementNo = #AgreementAno AND LhTransBalancePF.Baldate = #Baldate
--UPDATE LhTransBalancePF SET ProdName = Product.ProductName FROM LhTransBalancePF INNER JOIN Product
--ON LhTransBalancePF.ProdCode = Product.ProductCode
--WHERE AgreementNo = #AgreementAno AND BalDate = #Baldate
select #PrincipalBal = #ApprovedAmount, #PrincipalBalBccy = #ApprovedAmount , #InterestBal = 0 ,
#TrustBal = 0 , #TrustBalBccy = 0 , #OtherBal = 0 , #OtherBalBccy = 0 , #PrincipalArrears = 0 ,
#PrincipalArrearsBccy = 0 , #InterestArrears = 0 , #InterestArrearsBccy = 0 , #OtherArrears = 0 ,
#OtherArrearsBccy = 0 , #ArrearsInterest = 0 , #ArrearsInterestBccy = 0 , #MoOut = 0 ,
#PrinArrearsNotdue = 0 , #PrinArrearsNotdueBccy = 0 , #LastCreditDate = '1900-01-01' , #NoOFArr = 0 ,
#NoOfArrReal = 0 , #BaldateRep = '1900-01-01' , #DaysInArr = 0,#chargesSp =0
end
INSERT INTO LhTransBalance
(
BalDate, Currency, ExchangeRate, BaseNo, AgreementNo, Names, PostDate, Tranche , StartDate ,
FirstInstaldate , MaturityDate, Term, ApprovedAmount , PaymentFrequency , Rental ,
LastPaymentDate , NoOfArrears, ProdCode, ProdName , DaysInArrears, PrincipalBal ,
PrincipalBalBccy , InterestBal, InterestBalBccy , TrustBal , TrustBalBccy, OtherBal, OtherBalBccy ,
PrincipalArrears , PrincipalArrearsBccy , InterestArrears , InterestArrearsBccy , OtherArrears ,
OtherArrearsBccy, ArrearsInterest, ArrearsInterestBccy, MoOutstanding, PostingUser,LastAccrualdate ,
IntRate,PricipalArrearsNotDue,PrincipalArrNotDueBccy,NoOfArrearsReal, ChargesArrearsSp
)
VALUES
(
ISNULL(#BalDate,'1900-01-01') ,ISNULL(#MyCurrency,'') ,ISNULL(#MyRate,1) ,ISNULL(#Cno,'') , ISNULL(#AgreementAno,'') ,ISNULL(#Names,'') , ISNULL(#Baldate,'1900-01-01') , ISNULL(#Tranch,0) , ISNULL(#StartDate,'1900-01-01') ,
ISNULL(#FirstInstaldate,'1900-01-01') , ISNULL(#MaturityDate,'1900-01-01') , ISNULL(#Term,0) , ISNULL(#ApprovedAmount,0) ,3 ,iif(#Rental=null,0,#Rental) ,
#LastCreditDate , ISNULL(#NoOFArr,0) , '' , '' , ISNULL(#DaysInArr,0) , ISNULL(#PrincipalBal,0) ,
ISNULL(#PrincipalBalBccy,0) , ISNULL(#InterestBal,0) , ISNULL(#InterestBalBccy,0) , ISNULL(#TrustBal,0) ,ISNULL(#TrustBalBccy,0) ,ISNULL(#OtherBal,0), ISNULL(#OtherBalBccy,0) ,
ISNULL(#PrincipalArrears,0) , ISNULL(#PrincipalArrearsBccy,0) , ISNULL(#InterestArrears,0) , ISNULL(#InterestArrearsBccy,0) , ISNULL(#OtherArrears,0) ,
ISNULL(#OtherArrearsBccy,0) , ISNULL(#ArrearsInterest,0) , ISNULL(#ArrearsInterestBccy,0) , ISNULL(#MoOut,0) , 'SYSTEM',ISNULL(#BaldateRep,'1900-01-01') ,
ISNULL(#intRate,0),ISNULL(#PrinArrearsNotdue,0) ,ISNULL(#PrinArrearsNotdueBccy,0) ,ISNULL( #NoOfArrReal ,0) ,ISNULL( #chargesSp ,0)
)
update LHTransBalance set Registered = #Registered, RegisteredCollateral = #RegisteredCollateral,
ProdCode = #ProdCode ,loansizecategory = case when ApprovedAmount < = 5000000 then 'SMALL'
WHEN ApprovedAmount > 5000000 and ApprovedAmount < = 30000000 then 'MEDIUM'
ELSE 'LARGE' END
WHERE AgreementNo = #AgreementAno AND LhTransBalance.Baldate = #Baldate
--NO' 2017-09-19
update LhTransBalance set OldAno= pfagreements.oldagreementno, residualvalue = pfagreements.residualValue
from pfagreements inner join lhtransbalance on pfagreements.agreementno= LhTransBalance.agreementno
WHERE lhtransbalance.AgreementNo = #AgreementAno AND LhTransBalance.Baldate = #Baldate
--End
UPDATE LhTransBalance SET ProdName = Product.ProductName FROM LhTransBalance INNER JOIN Product
ON LhTransBalance.ProdCode = Product.ProductCode
WHERE AgreementNo = #AgreementAno AND BalDate = #Baldate
Fetch next from curAgreement1 into #AgreementAno
end
close curAgreement1
deallocate curAgreement1
Thank you for your help

Related

"IN Clause" causing "is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause."

I am having difficulty getting past this error message.
This query works:
declare
#warehouseID int =-1,
#type int=2, --0 = all; 1 = serial;2 = nonserial
#LocationID int =0
SELECT Sum(Quantity) AS Quantity,
WarehouseName,
WarehouseID,
sil.Location,
max(si.RecordID) as test,
min(si.RecordID) as test2,
-- (SELECT max(TransactionDate) from SS_Inventory_History sih2 where sih2.InventoryID in (SI.RecordID)
-- )
-- as test4,
(select max(Case When Serial_Number>'' Then COALESCE(si.SoldDate,'') else sih.TransactionDate end ) AS SoldDate
FROM SS_Inventory SI
JOIN SS_Inventory_Location SIL ON SIL.RecordID=SI.LocationID
LEFT JOIN SS_Inventory_Warehouse SIW ON SIW.RecordID =SIL.WarehouseID
Join SS_Inventory_History sih on InventoryID =sih.RecordID and sih.configStage = 7
WHERE
SIL.WarehouseID = CASE WHEN #warehouseID = -1 THEN SIL.WarehouseID ELSE #warehouseID END
AND SI.LocationID = CASE WHEN #LocationID = 0 THEN SI.LocationID ELSE #LocationID END
AND ((si.Quantity=0 and Serial_Number>'') or (Serial_Number=''))
and SIL.Active=1
AND (
(#type = 0 ) OR
(#type = 1 AND Serial_Number > '') OR
(#type = 2 AND COALESCE(Serial_Number,'')='')
)
) AS SoldDate,
max(si.ReceivedDate) AS ReceivedDate
FROM SS_Inventory SI
JOIN SS_Inventory_Location SIL ON SIL.RecordID=SI.LocationID
LEFT JOIN SS_Inventory_Warehouse SIW ON SIW.RecordID =SIL.WarehouseID
WHERE
SIL.WarehouseID = CASE WHEN #warehouseID = -1 THEN SIL.WarehouseID ELSE #warehouseID END
AND SI.LocationID = CASE WHEN #LocationID = 0 THEN SI.LocationID ELSE #LocationID END
AND Quantity>0
and SIL.Active=1
AND (
(#type = 0 ) OR
(#type = 1 AND Serial_Number > '') OR
(#type = 2 AND COALESCE(Serial_Number,'')='')
)
GROUP BY WarehouseName,
WarehouseID,
Location,
Part_Number,
Dist_Part_Num
but when i add/uncomment
(SELECT max(TransactionDate) from SS_Inventory_History sih2 where sih2.InventoryID in (SI.RecordID)
)
as test4,
so that it looks like
declare
#warehouseID int =-1,
#type int=2, --0 = all; 1 = serial;2 = nonserial
#LocationID int =0
SELECT Sum(Quantity) AS Quantity,
WarehouseName,
WarehouseID,
sil.Location,
--delete me?
max(si.RecordID) as test,
min(si.RecordID) as test2,
(SELECT max(TransactionDate) from SS_Inventory_History sih2 where sih2.InventoryID in (SI.RecordID)
)
as test4,
(select max(Case When Serial_Number>'' Then COALESCE(si.SoldDate,'') else sih.TransactionDate end ) AS SoldDate
FROM SS_Inventory SI
JOIN SS_Inventory_Location SIL ON SIL.RecordID=SI.LocationID
LEFT JOIN SS_Inventory_Warehouse SIW ON SIW.RecordID =SIL.WarehouseID
Join SS_Inventory_History sih on InventoryID =sih.RecordID and sih.configStage = 7
WHERE
SIL.WarehouseID = CASE WHEN #warehouseID = -1 THEN SIL.WarehouseID ELSE #warehouseID END
AND SI.LocationID = CASE WHEN #LocationID = 0 THEN SI.LocationID ELSE #LocationID END
AND ((si.Quantity=0 and Serial_Number>'') or (Serial_Number=''))
and SIL.Active=1
AND (
(#type = 0 ) OR
(#type = 1 AND Serial_Number > '') OR
(#type = 2 AND COALESCE(Serial_Number,'')='')
)
) AS SoldDate,
max(si.ReceivedDate) AS ReceivedDate
FROM SS_Inventory SI
JOIN SS_Inventory_Location SIL ON SIL.RecordID=SI.LocationID
LEFT JOIN SS_Inventory_Warehouse SIW ON SIW.RecordID =SIL.WarehouseID
WHERE
SIL.WarehouseID = CASE WHEN #warehouseID = -1 THEN SIL.WarehouseID ELSE #warehouseID END
AND SI.LocationID = CASE WHEN #LocationID = 0 THEN SI.LocationID ELSE #LocationID END
AND Quantity>0
and SIL.Active=1
AND (
(#type = 0 ) OR
(#type = 1 AND Serial_Number > '') OR
(#type = 2 AND COALESCE(Serial_Number,'')='')
)
GROUP BY WarehouseName,
WarehouseID,
Location,
Part_Number,
Dist_Part_Num
I get this error message:
Msg 8120, Level 16, State 1, Line 15
Column 'SS_Inventory.RecordID' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Does anyone have any idea what I am doing wrong?

Optimize multiple query separated by condition

I have a stored procedures with three different queries, that querys return values depending of received variable.
They basically return same data, just change WHERE clauses:
Query:
IF #DesignType = 'BDCD'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, CONVERT(BIT , IIF([DT].[DesignTypeGuid] = #ContractedDocument , 1 , 0)) AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND ([DT].[DesignTypeGuid] != IIF(#DesignTypeGuid = #ContractedDocument , #BidDocument , #ContractedDocument))
AND [DT].[DesignTypeGuid] != #ChangeOrder
AND [DT].[DesignTypeGuid] != #AddedPart
ORDER BY
[DT].[Order]
END
ELSE
BEGIN
IF #DesignType = 'CO'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, 0 AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND [DT].[DesignTypeGuid] = #ChangeOrder
ORDER BY
[DT].[Order]
END
ELSE
BEGIN
IF #DesignType = 'AP'
BEGIN
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, 0 AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND [DT].[DesignTypeGuid] = #AddedPart
ORDER BY
[DT].[Order]
END
Is there any way to optimize this and do it in a simple SELECT instead do 3 differents depending of DesignType variable? Regards
Not sure about the performance , but the query could definitely be written as
SELECT
[DT].[DesignTypeGuid]
, [DT].[Name]
, [DT].[Abbreviation]
, CASE #DesignType WHEN 'BDCD' THEN CONVERT(BIT , IIF([DT].[DesignTypeGuid] = #ContractedDocument , 1 , 0)) ELSE 0 END AS [EnforceBaseOnPrevious]
, [DT].[Order]
FROM [DesignType] AS [DT]
WHERE [DT].[IsActive] = 1
AND (
(
#DesignType = 'BDCD' AND [DT].[DesignTypeGuid] NOT IN ( IIF(#DesignTypeGuid = #ContractedDocument , #BidDocument , #ContractedDocument),#ChangeOrder,#AddedPart)
)
OR
(
#DesignType = 'CO' AND [DT].[DesignTypeGuid] = #ChangeOrder
)
OR
(
#DesignType = 'AP' AND [DT].[DesignTypeGuid] = #AddedPart
)
)
ORDER BY
[DT].[Order]

optimize complex stored procedure

I have a very complex stored procedure and i am not that strong in SQL, please any one who has a strong SQL expertise and can help me optimize or at least can give me a hint, the procedure selects the inbox messages from database for specific user and it contains many other parameters such as paging and categories and also language input and many other details:
ALTER PROCEDURE [dbo].[Inbox]
#ConfidentialityIds NVARCHAR(100) = '0,1,2,3',
#UrgencyIds NVARCHAR(100) = '0,1,2,3',
#CorrespondenceCategoryIds NVARCHAR(100) = '1,2,3,5,6,7',
#CorrespondenceExtendedCategoryIds NVARCHAR(MAX),
#IsPrivate bit = 0,
#IsSaved bit = 0,
#Importantance VARCHAR(10) = '0, 1',
#UserId uniqueidentifier,
#SelectedPage int = 1,
#PageSize int = 25,
#Now bigint,
#IsImpersonated bit,
#ActualLoggedInUserId uniqueidentifier,
#IsEnglish bit,
#OnlyArchived bit = null,
#replaceNameWithEntName bit,
#entityIds nvarchar(MAX),
#OnlyLate bit = 0,
#Statuses NVARCHAR(100) ='1,2,3,4,5',
#ApplyPageFilter bit = 1,
#IsBundled int,
#showArchivedInCCInbox bit = 0,
#appModuleId INT = 0
WITH RECOMPILE
As
BEGIN
SET transaction isolation level read uncommitted
DECLARE #lFirstRec INT, #lLastRec INT, #lTotalRows INT
SET #lFirstRec = ( #SelectedPage - 1 ) * #PageSize
SET #lLastRec = ( #SelectedPage * #PageSize + 1 )
SET #lTotalRows = #lFirstRec - #lLastRec + 1
DECLARE #isPersonalDelegationAvailable BIT = 0
IF EXISTS(
SELECT 1
FROM DelegatedToEntityUsers d
WHERE d.DelegatedToUserId = #ActualLoggedInUserId
AND d.DelegatedFromUserId = #UserId
AND
(
d.DelegatedToEntityId IS NULL OR d.DelegationType = 1
))
BEGIN
SET #isPersonalDelegationAvailable = 1
END
DECLARE #tblEntities TABLE(Value INT)
INSERT INTO #tblEntities
SELECT Value FROM SplitCommaUniqueValues(#entityIds)
Select * from (
Select (ROW_NUMBER() OVER (ORDER BY K.ActionDate DESC, K.CorrespondenceDate DESC)) AS RowIndex,
Count(*) over () AS TotalCount,*
from (
select (ROW_NUMBER() OVER (PARTITION BY CorrespondenceID Order by CorrespondenceID DESC)) AS CorrId, *
from (
SELECT Distinct * FROM
(
SELECT
CONVERT(VARCHAR(100), R.CorrespondenceActionRecipientID) Id,
A.CorrespondenceActionID ActionId,
(CASE WHEN R.RecipientType IS NULL THEN NULL ELSE CAST(RecipientType AS INT) END) RecipientType,
A.ActionTypeId,
(CASE when #IsEnglish = 1 then ATypes.FriendlyTextEN else ATypes.FriendlyTextAR end) ActionTypeName,
A.ActionCreatedByUserID SentById,
CASE
when #replaceNameWithEntName = 0 then ISNULL(ActionCreatedByUser.ShortName, ActionCreatedByUser.EmployeeName)
when #replaceNameWithEntName = 1 and SentByEntity.EntityID not in (SELECT Value FROM #tblEntities) then case when #IsEnglish = 1 then SentByEntity.EntityNameEn else SentByEntity.EntityNameAR end
when #replaceNameWithEntName = 1 and SentByEntity.EntityID in (SELECT Value FROM #tblEntities) then ISNULL(ActionCreatedByUser.ShortName, ActionCreatedByUser.EmployeeName)
END SentByFrom,
A.WithDelegateFromUserID OnBehalfOfId,
ISNULL(WithDelegateFromUser.ShortName, WithDelegateFromUser.EmployeeName) OnBehalfOfName,
R.UserId SentToId,
CASE
when #replaceNameWithEntName = 0 then ISNULL(SentToUser.ShortName, SentToUser.EmployeeName)
when #replaceNameWithEntName = 1 and SentToEntity.EntityID not in (SELECT Value FROM #tblEntities) then case when #IsEnglish = 1 then SentToEntity.EntityNameEn else SentToEntity.EntityNameAR end
when #replaceNameWithEntName = 1 and SentToEntity.EntityID in (SELECT Value FROM #tblEntities) then isnull(ISNULL(SentToUser.ShortName, SentToUser.EmployeeName), case when #IsEnglish = 1 then SentToEntity.EntityNameEn else SentToEntity.EntityNameAR end)
END SentToName,
R.EntityID SentToEntityId,
SentToEntity.EntityNameAR SentToEntityNameAR,
SentToEntity.EntityNameEN SentToEntityNameEN,
R.Seen,
(CASE WHEN MR.CorrespondenceActionRecipientID IS NOT NULL THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END) IsReadByUser,
CAST(ISNULL(FollowedByUser.IsFollowedByUser, 0) AS BIT) IsFollowedByUser,
(
CASE WHEN EXISTS(SELECT 1 FROM CorrespondenceFollowups
WHERE CorrespondenceID = C.CorrespondenceID
AND UserId = #UserId AND AssignedByUserId IS NOT NULL) THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
) IsAssignedFollowToUser,
(
CASE WHEN EXISTS(SELECT 1 FROM CorrespondenceFollowups
WHERE CorrespondenceID = C.CorrespondenceID
AND AssignedByUserId = #UserId) THEN CAST(1 AS BIT)
ELSE CAST(0 AS BIT) END
) IsAssignedFollowByUser,
A.CorrespondenceID,
A.ActionDate,
A.ActionDeadlineDate,
C.CompletionDate,
C.CorrespondenceDeadlineDate CorrDeadlineDate,
C.OwnerUserID CorrOwnerId,
C.ChildNo ChildNo,
OwnerUser.EmployeeName CorrOwnerName,
C.Important,
C.UrgencyId,
C.LetterCorrespondenceId,
(CASE when #IsEnglish = 1 then U.TextEN else U.TextAR end) UrgencyText,
C.ConfidentialityId,
(CASE when #IsEnglish = 1 then Confid.TextEN else Confid.TextAR end) ConfidentialityText,
C.CorrespondenceCategoryId CategoryId,
C.CorrespondenceClassificationID CorrespondenceClassificationID,
(CASE when #IsEnglish = 1 then CCat.TextEN else CCat.TextAR end) CategoryName,
CCat.ColorClass ColorClass,
C.Subject,
c.CorrespondenceFormula,
C.InternalSenderEntityId,
C.InternalRecipientEntityId,
C.[Sequence] [Sequence],
C.Year,
C.CompletionStatus Status,
Null Number,
(CASE WHEN (
(
(A.ActionDeadlineDate IS NOT NULL AND A.ActionDeadlineDate < #Now)
OR
(C.CorrespondenceDeadlineDate IS NOT NULL AND C.CorrespondenceDeadlineDate < #Now)
)
AND
C.[Closed-Archived] = 0) THEN CAST(1 AS BIT) ELSE CAST(0 AS BIT) END) IsLate,
CAST(0 AS BIT) HasAnyEvents,
C.CreatedByUserId,
CreatedByUser.EmployeeName CreatedByUserName,
CAST(C.CorrespondenceDate AS VARCHAR(50)) CorrDate,
C.CorrespondenceDate,
C.[Closed-Archived] ClosedArchived,
C.IsSaved SavedActionTaken,
((CASE WHEN C.Important = 1 THEN CASE WHEN #IsEnglish = 1 THEN N'Important' ELSE N'هامة' END ELSE '' END) + (CASE WHEN C.Important = 1 AND C.UrgencyID <> 0 THEN CASE WHEN #IsEnglish = 1 THEN N' and ' ELSE N' و ' END ELSE '' END) + (CASE WHEN C.UrgencyID <> 0 THEN (CASE when #IsEnglish = 1 then U.TextEN else U.TextAR end) ELSE '' END)) ImportantUrgencyText,
CAST(C.IsAutoSaved AS BIT) IsAutoSaved,
-- *******************************************************************
rem.ReminderDate as CorrespondenceReminderDateTime,
remAction.ReminderDate as ActionReminderDateTime
FROM (
SELECT * FROM Correspondences CC
WHERE CC.IsDeleted = 0
AND CC.LetterCorrespondenceId IS NULL
AND (CC.ConfidentialityId IN (SELECT [Value] FROM SplitCommaUniqueValues(#ConfidentialityIds)))
AND
( #IsPrivate = 0 OR
(
#IsPrivate = 1 AND CC.IsForPresident = 1
)
)
AND
(
(CC.IsSaved = case when #IsSaved =1 then 1 else CC.IsSaved end)
)
AND (#appModuleId = 0 OR CC.AppModuleId = #appModuleId)
AND (CC.UrgencyID IN (SELECT value FROM SplitCommaUniqueValues(#UrgencyIds)))
AND (CC.Important IN (SELECT value FROM SplitCommaUniqueValues(#Importantance)))
AND CC.CompletionStatus IN(SELECT value FROM SplitComma(#Statuses))
) C
LEFT JOIN CorrespondenceExtendedDetails CorrExt
ON CorrExt.CorrespondenceID = C.CorrespondenceID
LEFT JOIN CorrespondenceActions A
ON C.CorrespondenceID = A.CorrespondenceID
AND A.IsDeleted = 0
AND A.ActionTypeID != 7 -- إنهاء التذكير
LEFT JOIN CorrespondenceActionRecipients R
ON A.CorrespondenceActionID = R.CorrespondenceActionID
AND (
R.AsCopy = 1
)
JOIN Urgencies U
ON C.UrgencyID = U.ID
JOIN ActionTypes ATypes
ON A.ActionTypeID = ATypes.ID
JOIN CorrespondenceCategories CCat
ON C.CorrespondenceCategoryId = CCat.ID
JOIN Confidentialities Confid
ON C.ConfidentialityID = Confid.ID
LEFT JOIN Users ActionCreatedByUser
ON A.ActionCreatedByUserID = ActionCreatedByUser.UserId
LEFT JOIN Users WithDelegateFromUser
ON A.WithDelegateFromUserID = WithDelegateFromUser.UserID
LEFT JOIN Entities SentByEntity
ON A.ActionCreatedByUserEntityId = SentByEntity.EntityID
LEFT JOIN Users SentToUser
ON R.UserId = SentToUser.UserId
LEFT JOIN Entities SentToEntity
ON R.EntityID = SentToEntity.EntityID
LEFT JOIN Users OwnerUser
ON C.OwnerUserID = OwnerUser.UserId
LEFT JOIN Users CreatedByUser
ON C.CreatedByUserID = CreatedByUser.UserId
LEFT JOIN MarkAsReads MR
ON R.CorrespondenceActionRecipientID = MR.CorrespondenceActionRecipientID
AND MR.UserId = #UserId
OUTER APPLY
(
SELECT TOP 1 1 IsFollowedByUser
FROM CorrespondenceFollowups CF
WHERE CF.CorrespondenceId = C.CorrespondenceID
AND CF.UserId = #UserId
AND CF.AssignedByUserId IS NULL
) FollowedByUser
-- *******************************************************************
LEFT JOIN LinkedCorrespondenceSchedules CS on CS.CorrespondenceID = C.CorrespondenceID
LEFT JOIN Reminder rem on rem.ReferenceId=C.CorrespondenceID AND rem.ReferenceType = 1 AND rem.CreatedByUserId=#UserId AND (rem.[Status] = 1 OR rem.[Status] = 2)
Left JOIN Reminder remAction on remAction.ReferenceId = A.CorrespondenceActionID AND remAction.ReferenceType = 2 AND remAction.CreatedByUserId=#UserId AND (remAction.[Status] = 1 OR remAction.[Status] = 2)
-- *******************************************************************
WHERE (
(C.CorrespondenceCategoryId IN (SELECT Value FROM SplitComma(#CorrespondenceCategoryIds)) AND CorrExt.CorrespondenceExtendedCategoryId IS NULL)
OR (CorrExt.CorrespondenceExtendedCategoryId IN (SELECT Value FROM SplitComma(#CorrespondenceExtendedCategoryIds)))
)
AND
(
-- Personal
(
(
(#IsImpersonated = 0 AND R.UserId = #UserId)
OR
(#IsImpersonated = 1 AND R.UserId = #UserId AND #isPersonalDelegationAvailable = 1)
)
AND R.RecipientType = 1 AND R.UserId Is Not null
)
OR
-- Me as Manager (Impersonation mode handled from code by sending the proper Entity Ids.
(
(R.EntityID IN (SELECT Value FROM #tblEntities) AND R.EntityID Is Not null AND R.RecipientType != 1)
)
)
AND C.[Closed-Archived] = Case When #showArchivedInCCInbox = 1 Then 0 Else C.[Closed-Archived] End
AND R.UserTokeAction = 0
AND NOT EXISTS (
SELECT 1 FROM Correspondences CC
INNER JOIN CorrespondenceLinks CL
ON CC.CorrespondenceID = CL.LinkedCorrespondenceID AND CC.CorrespondenceID = C.CorrespondenceID AND CL.LinkTypeID = #IsBundled
)
) T
WHERE T.LetterCorrespondenceId is null
) as ttt
) K where CorrId = 1
)N where (#ApplyPageFilter = 0 OR ( RowIndex > #lFirstRec AND RowIndex < #lLastRec))
Order by
ActionDate DESC, CorrespondenceDate
option(recompile)
END

Improve case statement in order clause

I have the store sql
ALTER procedure [dbo].[TNNews_User_SearchBasic]
#Title nvarchar(400),
#CategoryId int,
#IsInterested int,
#IsHot int,
#IsTopCategory int,
#IsPublish int,
#PageSize int,
#PageIndex int,
#OrderBy varchar(20),
#PortalId int,
#LanguageId varchar(6)
as
DECLARE #EndTime DATETIME
DECLARE #StartTime DATETIME
SET #StartTime = GETDATE()
declare #tbCategory table(Id int)
DECLARE #StartRowIndex INT
IF #PageSize=0 SELECT #PageSize=count(*) FROM TNNews
IF(#PageIndex<0) SET #PageIndex=0
SET #StartRowIndex = #PageSize*(#PageIndex-1)+1
;WITH tmpCategory(Id, Name,ParentId,Level)
AS (
SELECT
e.Id,
e.Name,
e.ParentId,
1
FROM dbo.TNCategory AS e
WHERE
Id = #CategoryId or (#CategoryId='' and ParentId<=0)
UNION ALL
SELECT
e.Id,
e.Name,
e.ParentId,
Level + 1
FROM dbo.TNCategory AS e
JOIN tmpCategory AS d ON e.ParentId = d.Id
)
insert #tbCategory select Id from tmpCategory
;WITH tmpNews as
(
SELECT
a.Id,a.Title,a.Subject
,ROW_NUMBER() OVER (ORDER BY (Publisheddate) desc) as ThuTuBanGhi
FROM dbo.TNNews a
where 1 = 1
--and ( Title like '%'+#Title+'%')
and (#CategoryId = -1 or exists (select 0 from #tbCategory b where b.Id = a.CategoryId))
and (#IsInterested = -1 or IsIntrested = #IsInterested )
and (#IsHot = -1 or IsHot = #IsHot )
and (#IsTopCategory = -1 or IsTopCategory = #IsTopCategory )
and (#IsPublish = -1 or IsPublished = #IsPublish)
and PortalId=#PortalId
and LanguageId = #LanguageId
)
select *, (select COUNT(Id) from tmpNews) as 'TongSoBanGhi' from tmpNews
WHERE
ThuTuBanGhi BETWEEN (#StartRowIndex) AND (#StartRowIndex + #PageSize-1)
SET #EndTime = GETDATE()
PRINT 'StartTime = ' + CONVERT(VARCHAR(30),#StartTime,121)
PRINT ' EndTime = ' + CONVERT(VARCHAR(30),#EndTime,121)
PRINT ' Duration = ' + STR(DATEDIFF(MILLISECOND,#StartTime,#EndTime)) + ' millisecond'
select STR(DATEDIFF(MILLISECOND,#StartTime,#EndTime))
After this store excute
EXEC [dbo].[TNNews_User_SearchBasic]
#Title='',
#CategoryId = '',
#IsInterested = -1,
#IsHot = -1,
#IsTopCategory = -1,
#IsPublish = -1,
#PageSize = 20,
#PageIndex = 1,
#OrderBy = '',
#PortalId = 0,
#LanguageId = N'vi-VN'
go
The time excute about "200ms". And I create a new store "TNNews_User_SearchBasic1" with some change.
.....
--,ROW_NUMBER() OVER (ORDER BY (Publisheddate) desc) as ThuTuBanGhi
,ROW_NUMBER() OVER (ORDER BY (case when #OrderBy='VIEW_COUNT' then ViewCount else PublishedDate end) desc) as ThuTuBanGhi
.....
and now the time excute this store
EXEC [dbo].[TNNews_User_SearchBasic1]
#Title='',
#CategoryId = '',
#IsInterested = -1,
#IsHot = -1,
#IsTopCategory = -1,
#IsPublish = -1,
#PageSize = 20,
#PageIndex = 1,
#OrderBy = '',
#PortalId = 0,
#LanguageId = N'vi-VN'
GO
about 900ms.
I don't understand why there is a change. Please help me improve these stores.
PS: I put example db at: http://anhquan22.tk/Portals/0/Videos/web.rar
Finished analysis the structure of your database. The part of the problem is hiding in the table structure.
I have prepared a backup for you. In it, I slightly modified scheme to improve performance and some normalize the table. You can download it from this link.
...to your question, I would do like this -
DECLARE #SQL NVARCHAR(1000)
SELECT #SQL = N'
;WITH tmpCategory (Id, Name, ParentId, [Level]) AS
(
SELECT
e.Id
, e.Name
, e.ParentId
, 1
FROM dbo.TNCategory e
WHERE Id = #CategoryId OR (#CategoryId = '''' AND ParentId <= 0)
UNION ALL
SELECT
e.Id
, e.Name
, e.ParentId
, [Level] + 1
FROM dbo.TNCategory e
JOIN tmpCategory d ON e.ParentId = d.Id
)
SELECT
a.Id
, ROW_NUMBER() OVER (ORDER BY ' +
CASE WHEN #OrderBy = 'VIEW_COUNT'
THEN 'ViewCount'
ELSE 'PublishedDate'
END +' DESC) AS ThuTuBanGhi
FROM dbo.TNNewsMain a
where PortalId = #PortalId
AND LanguageId = #LanguageId'
+ CASE WHEN #IsInterested != -1 THEN ' AND IsInterested = #IsInterested' ELSE '' END
+ CASE WHEN #IsHot != -1 THEN ' AND IsHot = #IsHot' ELSE '' END
+ CASE WHEN #IsTopCategory != -1 THEN ' AND IsTopCategory = #IsTopCategory' ELSE '' END
+ CASE WHEN #IsPublish != -1 THEN ' AND IsPublish = #IsPublish' ELSE '' END
+ CASE WHEN #CategoryId != -1 THEN '' ELSE ' AND EXISTS(SELECT 1 FROM tmpCategory b WHERE b.Id = a.CategoryId)' END
INSERT INTO #temp (Id, ThuTuBanGhi)
EXECUTE sp_executesql
#SQL
, N'#PortalId INT
, #LanguageId VARCHAR(6)
, #CategoryId INT
, #IsInterested INT
, #IsHot INT
, #IsTopCategory INT
, #IsPublish INT'
, #PortalId = #PortalId
, #LanguageId = #LanguageId
, #CategoryId = #CategoryId
, #IsInterested = #IsInterested
, #IsHot = #IsHot
, #IsTopCategory = #IsTopCategory
, #IsPublish = #IsPublish;
SELECT
d.Id
, tm.Title
, tm.[Subject]
, d.ThuTuBanGhi
, c.TongSoBanGhi
FROM (
SELECT t.Id
, t.ThuTuBanGhi
FROM #temp t
WHERE t.ThuTuBanGhi BETWEEN #StartRowIndex AND #StartRowIndex + #PageSize - 1
) d
JOIN TNNewsMain tm ON d.Id = tm.Id
CROSS JOIN (
SELECT TongSoBanGhi = (SELECT COUNT(1) FROM #temp)
) c

Query Runs Slower The Second Time

I have this massive query that I can typically run in under 2 minutes. However, when I run it a second time about a minute after, it goes on infinitely... so I kill the process and my SSMS session. I don't have any other jobs running in the background.
Is something else being retained on the server? I think I'm missing something as far as how SQL Server works.
Thanks.
EDIT: Here's the SQL (had to do a little obfuscation)
SELECT pl.OrangeLocationID ,
e.EventID ,
cr.Title AS [Event Type] ,
su.LastName + ', ' + su.FirstName AS FMR ,
CONVERT(VARCHAR(20), pl.Report_Date, 101) AS [Report Entry Date] ,
l.Name ,
l.Number ,
ll.SodaPopLocationID AS [SodaPop Location ID] ,
l.Zip ,
c.Channel ,
pl.DT AS [ReportedDate] ,
RIGHT(pl.DT_start, 8) AS [ReportedStartTime] ,
RIGHT(pl.DT_end, 8) AS [ReportedEndTime] ,
[CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) AS [ReportedDuration] ,
pl.scheduled_date AS [ScheduledDate] ,
RIGHT(pl.scheduled_start, 8) AS [ScheduledStartTime] ,
RIGHT(pl.scheduled_end, 8) AS [ScheduledEndTime] ,
[CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) AS [ScheduledDuration] ,
e.HoursPaid AS [Rep Hours Worked] ,
ISNULL(PP.[RepCount], 0) AS [RepCount] ,
CASE WHEN [CMS].dbo.dDateDiff(pl.DT_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.DT_start, pl.DT_end)
WHEN [CMS].dbo.dDateDiff(pl.scheduled_start, pl.DT_end) = ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
THEN [CMS].dbo.oa_HourDateDiff(pl.scheduled_start, pl.DT_end)
ELSE ( e.HoursPaid / ISNULL(PP.[RepCount], 1) )
END AS [FinalDuration] ,
g.[Description] AS [OA Market] ,
g.SodaPop_Region AS [SodaPop Region] ,
g.SodaPop_Area AS [SodaPop Area] ,
coup4 ,
coupo ,
coupo_e ,
card_num ,
promo ,
promo_no ,
promo_no_o ,
highlight1 ,
highlight2 ,
highlight3 ,
mgmt_reaction ,
mgmt_reaction_e ,
comm_p ,
comm_n ,
r.comments ,
s_fname ,
s_lname ,
v_title ,
ll.KeyAccountCorp AS [Key Account Corp.] ,
interact_new + interact_rep AS [interact_total] ,
samp_new + samp_rep AS [samp_total] ,
purch_new + purch_rep AS [purch_total] ,
23 / ( NULLIF(( interact_new + interact_rep ), 0) * 1.0 ) AS [Int_Crate] ,
CASE WHEN sampletype = 11 THEN ( purch_new + purch_rep ) / ( NULLIF(( samp_new + samp_rep ), 0) * 1.0 )
ELSE NULL
END AS [Samp_Crate] ,
coup1 + coup2 AS [coup_total] ,
CASE WHEN coup1 + coupo > 0 THEN 1
ELSE 0
END AS [CoupDist] ,
DATEPART(month, pl.DT) AS [Visit_Month] ,
DATEPART(quarter, pl.DT) AS [Quarter] ,
DATEPART(weekday, pl.DT) AS [Weekday] ,
CASE DATEPART(weekday, pl.DT)
WHEN 6 THEN 'Fri'
WHEN 7 THEN 'Sat'
WHEN 1 THEN 'Sun'
ELSE 'Mon-Thurs'
END AS [Weekday_Grouped] ,
CASE WHEN dbo.Exception(pl.OrangeLocationID, 12) = 1
OR dbo.Exception(pl.OrangeLocationID, 13) = 1
OR dbo.Exception(pl.OrangeLocationID, 14) = 1 THEN 1
ELSE 0
END AS [EVolume] ,
CASE WHEN dbo.DoesHaveException(pl.OrangeLocationID, 18) = 1 THEN 1
ELSE 0
END AS [CVolume] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 9) = 1
OR dbo.eException(pl.OrangeLocationID, 22) = 1 THEN 1
ELSE 0
END AS [Volumes] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 8) = 1
OR dbo.eException(pl.OrangeLocationID, 21) = 1 THEN 1
ELSE 0
END AS [Sales Price] ,
CASE WHEN dbo.eException(pl.OrangeLocationID, 11) = 1 THEN 1
ELSE 0
END AS [Sample Volume] ,
ISNULL(i.[NormalizedSold], 0) AS [EQBottlesSold] ,
CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END AS [EQBottlesSoldPerPurch] ,
ac.AvgSales ,
ac.STDEVSales ,
( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales AS [sl] ,
ac.AvgPurchasers ,
ac.STDEVPurchasers ,
( ISNULL(r.purch_new, 0) - ac.AvgPurchasers ) / ac.STrchasers AS [ZScore_Purchasers] ,
ac.AvgConversions ,
ac.STDEVConversions ,
( ISNULL(( purch_new + purch_rep ) / ( NULLIF(( interact_new ), 0) ), 0) - ac.AvgConversions )
/ ac.STDEVConversions AS [ZScore_Conversions] ,
ac.[AvgSalesPerPurchaser] ,
ac.[STDEVSalesPerPurchaser] ,
( ISNULL(( CASE WHEN ISNULL(purch_new, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser] ) / ac.[STDEVSalesPerPurchaser] AS [SalesPerPurchaser] ,
( ( ( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales )
+ ( (ISNULL(( CASE WHEN ISNULL(purch_new + purch_rep, 0) = 0 THEN 0
ELSE ISNULL(i.[NormalizedSold], 0) / ( purch_new + purch_rep )
END ), 0) - ac.[AvgSalesPerPurchaser]) ) ) / 4 AS [core] ,
( ( (( ISNULL(i.[NormalizedSold], 0) - ac.AvgSales ) / ac.STDEVSales) ) / 4 ) + 3 AS [core] ,
su.aaUserID ,
l.LsocationID
FROM [CMS_SodaPop].dbo.Schedule pl WITH ( NOLOCK )
INNER JOIN [CMS_SodaPop].dbo.Report r WITH ( NOLOCK ) ON r.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS].dbo.Users su WITH ( NOLOCK ) ON su.UserID = pl.Rep_FMR
INNER JOIN [CMS].dbo.Locations l WITH ( NOLOCK ) ON l.LocationID = pl.LocationID
INNER JOIN [CMS].dbo.OrangeReports cr WITH ( NOLOCK ) ON cr.RedID = pl.RedID
INNER JOIN [CMS_SodaPop].dbo.Events e WITH ( NOLOCK ) ON e.OrangeLocationID = pl.OrangeLocationID
INNER JOIN [CMS_SodaPop].dbo.MarketList g WITH ( NOLOCK ) ON g.GroupID = pl.GroupID
INNER JOIN [CMS_SodaPop].dbo.Locations ll WITH ( NOLOCK ) ON ll.LocationID = pl.LocationID
LEFT JOIN [CMS_SodaPop].dbo.Channels c WITH ( NOLOCK ) ON ll.ChannelID = c.ChannelID
LEFT JOIN ( SELECT PLocationID ,
COUNT(DISTINCT UserID) AS [RepCount]
FROM [CMS_roll].dbo.rollItems WITH ( NOLOCK )
WHERE RedID = 154
GROUP BY OrangeLocationID
) PP ON PP.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN ( SELECT OrangeLocationID ,
SUM(NormalizedSold) AS [NormalizedSold]
FROM [Analysis].dbo.[vSodaPop_Retail_Inventory] WITH ( NOLOCK )
GROUP BY OrangeLocationID
) i ON i.OrangeLocationID = pl.OrangeLocationID
LEFT JOIN [Analysis].dbo.[vSodaPop_Calculations] ac WITH ( NOLOCK ) ON ac.[Quarter] = CASE WHEN DATEPART(MM,
[DT]) IN ( 10,
11, 12 ) THEN 4
END
AND ac.[Year] = DATEPART(YY, pl.DT)
WHERE pl.Activity = 1
AND pl.RedID = 154
AND pl.GroupID <> 444
AND pl.[DT] < GETDATE()
AND DATEPART(YY, [DT]) >= 2010
AND ISNULL(i.NormalizedSold, 0) >= 0
AND DATEPART(year, GETDATE()) = DATEPART(year, r.Insert_Date)
Would have to see the query to really dig in however..
you could try adding OPTION (RECOMPILE) to the end of the query to force it to create a new execution plan.
Are you using Temp Tables?
Cursors not deallocated & closed?
You can look at Profiler to see if anything looks different between the 2 executions.
Are you sure it isn't being blocked by another process the second time?
What happens if you execute
CHECKPOINT;
GO;
DBCC DROPCLEANBUFFERS;
GO;
DBCC FREEPROCCACHE;
GO;
between the queries? This is not really a solution but will help diagnosis.