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
When I'm trying to convert this piece of SQL to LINQ, I received this error:
SQL cannot be converted to LINQ: Table [GL] not found in the current
Data Context.
But in SQL it works fine.
This is my SQL query:
SELECT itm.Id ,
ISNULL(itm.Debit, 0) AS Debit ,
ISNULL(itm.Credit, 0) AS Credit ,
itm.State ,
itm.DocCreateDate ,
ISNULL(itm.Num, 0) AS Num ,
ISNULL(itm.DocTypeRef, 0) AS DocTypeRef ,
itm.Year ,
itm.Month ,
ISNULL(itm.DebitCount, 0) AS DebitCount ,
ISNULL(itm.CreditCount, 0) AS CreditCount ,
itm.DL ,
itm.DL2 ,
itm.DL3 ,
itm.DL4 ,
itm.DL5 ,
itm.DL6 ,
itm.DL7 ,
ISNULL(itm.FCRef, 0) AS FCRef ,
itm.FollowUpNum ,
ISNULL(itm.BranchRef, 1) AS BranchRef ,
itm.DocHeaderRef ,
ISNULL(itm.RowNum, 0) AS RowNum ,
ISNULL(itm.DailyNum, 0) AS DailyNum ,
ISNULL(itm.TempNum, 0) AS TempNum ,
ISNULL(itm.RefNum, 0) AS RefNum ,
itm.Descript ,
itm.Count ,
itm.FollowUpDate ,
itm.FCVal ,
itm.FCRateVal ,
itm.FactorNum ,
ISNULL(itm.DebitFCVal, 0) AS DebitFCVal ,
ISNULL(itm.CreditFCVal, 0) AS CreditFCVal ,
sl.Id AS SLRef ,
sl.SLCode ,
sl.Title AS SLTitle ,
CASE WHEN ISNULL(sl.DLSRef, 0) > 0 THEN 1
ELSE 0
END AS HasDL ,
CASE WHEN ISNULL(sl.DLSRef2, 0) > 0 THEN 1
ELSE 0
END AS HasDL2 ,
CASE WHEN ISNULL(sl.DLSRef3, 0) > 0 THEN 1
ELSE 0
END AS HasDL3 ,
CASE WHEN ISNULL(sl.DLSRef4, 0) > 0 THEN 1
ELSE 0
END AS HasDL4 ,
CASE WHEN ISNULL(sl.DLSRef5, 0) > 0 THEN 1
ELSE 0
END AS HasDL5 ,
CASE WHEN ISNULL(sl.DLSRef6, 0) > 0 THEN 1
ELSE 0
END AS HasDL6 ,
CASE WHEN ISNULL(sl.DLSRef7, 0) > 0 THEN 1
ELSE 0
END AS HasDL7 ,
CASE WHEN ISNULL(sl.HasFC, 0) > 0 THEN 1
ELSE 0
END AS HasFC ,
1 AS HasFollow ,
tl.Id AS TLRef ,
tl.Title AS TLTitle ,
tl.TLCode ,
gl.Id AS GLRef ,
gl.Title AS GLTitle ,
gl.GLCode ,
gl.Balance AS GLBalance
FROM Acc.DocItem AS itm
LEFT OUTER JOIN Acc.SL AS sl ON itm.SLRef = sl.Id
LEFT OUTER JOIN Acc.TL AS tl ON sl.TLRef = tl.Id
LEFT OUTER JOIN Acc.GL AS gl ON tl.GLRef = gl.Id
WHERE ( itm.SLRef > 0 )
If there is no way to pass this error so can you tell me its LINQ equal?
There is a way to do that in linq:
var q =
from c in categories
join p in products on c.Category equals p.Category into ps
from p in ps.DefaultIfEmpty()
select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };
This is the big idea for left outer join, you as the syntax for 'into' like 'as' in SQL query.
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.