I have legacy SQL (SP)
declare @FactorCollectionId int; select @FactorCollectionId = collectionID from dbo.collection where name = 'Factor'
declare @changeDate datetime; set @changeDate = getDate()
declare @changeTimeID int; set @changeTImeID = convert(int, convert(varchar(8), @changeDate, 112))
declare @MaxWindowID int; select @MaxWindowID = MAX(windowID) from dbo.window
select distinct @FactorCollectionId, ElementId, T.TimeID, @changeTimeId ChangeTimeID, 1 UserID, @MaxWindowID, 0 ChangeID
, null TransactionID, SystemSourceID, changeTypeID, 'R' OlapStatus, Comment, Net0 Delta0, Net0
, 1 CreatedBy, 1 UpdatedBy, @changeDate CreatedDate, @changeDate UpdatedDate, 1 CurrentRecord, MeasureTypeID
from dbo.aowCollectedFact FV
inner join dbo.timeView T on T.timeID >= FV.timeID
where FV.currentRecord = 1
and T.CurrentHorizon <> 0
and FV.collectionID = @FactorCollectionId
and FV.timeID = (select MAX(timeID)
from aowCollectedFact FV2
where FV2.collectionId = @FactorCollectionId
and FV2.elementId = FV.elementID)
and (((T.ForecastLevel = 'Month') and (T.FirstDayInMonth = T.Date))
or
((T.ForecastLevel = 'Quarter')and (T.FirstDayInQuarter = T.Date)))
and not exists (select 1
from aowCollectedFact FV3
where FV3.collectionId = @FactorCollectionId
and FV3.elementID = FV.elementId
and FV3.timeID = T.timeID)
This SQL processes over 2 million rows. I need to improve his work. When I look at the execution plan, I find that a lot of time is spent on the operation Table Spool (Lazy spool)(indexes exist in tables, and they work well).
How to improve performance for this part?
source
share