0

我在 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);
4

1 回答 1

0

[Status] 字段将没有索引,因为它是在 WITH 子句中创建的。我会建议您不要在 WHERE 子句中使用 [Status] 字段

cast((case when ((tbl.Debit > 0 and cte.Debit>cte.Credit)) then abs(cte.Balance + tbl.Debit)
                when tbl.Debit > 0 and cte.Debit<=cte.Credit then abs(cte.Balance - tbl.Debit)
                when(tbl.Credit > 0 and cte.Debit>cte.Credit) then abs(cte.Balance - tbl.Credit)
                when(tbl.Credit > 0 and cte.Debit<=cte.Credit) then abs(cte.Balance + tbl.Credit)
                                end )as decimal(18,0))
于 2014-09-15T07:54:16.110 回答