用递归CTE替换while循环

时间:2020-01-22 00:43:04

标签: sql-server optimization while-loop common-table-expression recursive-cte

我有一个while循环脚本,该脚本检查临时日期表中的日期列表,一直运行到遍历表中的所有日期为止。目的是为临时表中的每个报告日期提取不同时间范围的余额(当前余额和上月余额)。

有人告诉我要避免while循环,并且脚本运行时为20分钟(数百万个数据),我希望可以用递归CTE代替它,但不确定我的情况。

请查看我当前的脚本示例并提出建议。

declare @LatestBusDay date = '1/17/20'
declare @rolling2 date = (select prior_bus_day from datefunction(@LatestBusDay))
declare @rolling3 date = (select prior_bus_day from datefunction(@rolling2))

create table #reportingDates (process_dt date)
insert into #reportingDates 
    select @LatestBusDay
    union select @rolling2
    union select @rolling3

while exists (select * from #reportingDates)
begin

set @dt = (select top 1 process_dt from #reportingDates)
set @tmp_priorMth = (select prior_mth_end from datefunction(@dt)) --getting prior month-end from given @dt

--pull current balance
insert into #balances
select current_balance, 0 as prior_mth_balance
from balancetable
where process_dt=@dt

--pull prior month balance
insert into #balances
select 0 as current_balance, prior_mth_balance
from balancetable
where process_dt=@tmp_priorMth

--aggregate into #result with each loop's reporting date stamp
insert into #result
select sum(current_balance), sum(prior_mth_balance), @dt as report_as_of
from #balances

delete top (1) from #reportingDates
end

0 个答案:

没有答案
相关问题