【问题标题】:Low performance set based storedprocedure基于低性能集的存储过程
【发布时间】:2014-11-08 14:57:39
【问题描述】:

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

【问题讨论】:

    标签: sql performance stored-procedures set-based


    【解决方案1】:

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

    【讨论】:

    • 你的意思是删除第 4,5,6,7 行???所以让我知道如何在第 14 行设置状态字段??
    • 第 14 行到底是什么?还是 4,5,6,7?我的意思是尽管使用 [Status] 你应该使用借方和贷方字段。在第二种情况下-您可以存储上一个文档中的这些数据-尽管计数并存储 STATUS 字段。
    • 我尝试了您的解决方案,但对性能没有影响!!
    • 但我需要存储状态字段以在我的用户报告中显示
    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多