0

I am using following set based code in sql to calculate the customers bill but it takes 3 Min to performs the operation on 40000 records !!! let me know what is the problem ???

 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);
franchesco totti
  • 582
  • 1
  • 7
  • 28

1 Answers1

0

The [Status] field will not have index, because it created in WITH clause. I will recomend you not to use [Status] field in your WHERE clause

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))
MikkaRin
  • 3,026
  • 19
  • 34