У меня есть устаревший 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 --is current record
and T.CurrentHorizon <> 0 --Indicator that Time is part of current horizon
and FV.collectionID = @FactorCollectionId --factor collections only
and FV.timeID = (select MAX(timeID) --latest collected fact timeID for given collectionID and elementID
from aowCollectedFact FV2
where FV2.collectionId = @FactorCollectionId
and FV2.elementId = FV.elementID)
and (((T.ForecastLevel = 'Month') and (T.FirstDayInMonth = T.Date)) --Date is first of month for monthly customers, or
or
((T.ForecastLevel = 'Quarter')and (T.FirstDayInQuarter = T.Date))) --Date is first of quarter for quarterly customers
and not exists (select 1 --Record does not already exist in collected fact view
from aowCollectedFact FV3 -- for this factor collection, elementID, and timeID
where FV3.collectionId = @FactorCollectionId
and FV3.elementID = FV.elementId
and FV3.timeID = T.timeID)
Этот SQL обрабатывает более 2 миллионов строк. Мне нужно улучшить его работу. Когда я смотрю на план выполнения, я обнаруживаю, что много времени тратится на операцию Table Spool (Lazy spool)
(индексы существуют в таблицах и работают хорошо).
Как повысить производительность этой части?