SQL で次のセットベースのコードを使用して顧客の請求書を計算していますが、40000 レコードで操作を実行するには 3 分かかります!!! 何が問題なのか教えてください???
with cte (ID,[Date],Time,DocumentNumber,Title,TopicFK,Description,DocumentHeaderID,Debit,Credit,Balance,[Status])
as
(
select ID,[Date],Time,DocumentNumber,Title,TopicFK,Description,DocumentHeaderID,Debit, Credit, Balance=(case when (Debit>Credit) then abs(Debit) else abs(Credit) end), [Status]=cast((case when (Debit>Credit) then 'Debit' else 'Credit' end)as nvarchar(10))
from #t1
where ID = 1
union all
select tbl.ID,tbl.[Date],tbl.Time,tbl.DocumentNumber,tbl.Title,tbl.TopicFK,tbl.Description,tbl.DocumentHeaderID,tbl.Debit, tbl.Credit
, Balance=cast((case when ((tbl.Debit > 0 and cte.[Status] = 'Debit')) then abs(cte.Balance + tbl.Debit)
when tbl.Debit > 0 and cte.[Status] = 'Credit' then abs(cte.Balance - tbl.Debit)
when(tbl.Credit > 0 and cte.[Status] = 'Debit') then abs(cte.Balance - tbl.Credit)
when(tbl.Credit > 0 and cte.[Status] = 'Credit') then abs(cte.Balance + tbl.Credit)
end )as decimal(18,0))
, cast((case when ((tbl.Debit > 0 and cte.[Status] = 'Debit')) then 'Debit'
when tbl.Debit > 0 and cte.[Status] = 'Credit' then 'Credit'
when(tbl.Credit > 0 and cte.[Status] = 'Debit') then 'Debit'
when(tbl.Credit > 0 and cte.[Status] = 'Credit') then 'Credit'
end )as nvarchar(10)) as [Status]
from #t1 tbl
inner join cte cte
on tbl.ID = cte.ID + 1
)
select [Date],Time,DocumentNumber,Title,TopicFK,Description,DocumentHeaderID, Debit, Credit, Balance, [Status] from cte
option (maxrecursion 0);