基于低性能集的存储过程

时间:2014-09-15 06:27:46

标签: sql performance stored-procedures set-based

我在sql中使用以下基于集合的代码来计算客户账单,但需要3分钟才能对40000条记录执行操作!让我知道是什么问题???

 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);

1 个答案:

答案 0 :(得分: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))