troubleshooting Question

improve query (where with case when)

Avatar of Edgard Yamashita
Edgard YamashitaFlag for Brazil asked on
Microsoft SQL ServerMicrosoft SQL Server 2005SQL
15 Comments1 Solution282 ViewsLast Modified:
i have this query:

select sum(coalesce(PaidDeals.Value,0)) from
            T_Deals Deals inner join T_PaidDeals PaidDeals on PaidDeals.DealId = Deals.DealId and PaidDeals.Valid = 1
                  where  Deals.IdMain = @IdMain  and
                  datediff(dd, 0, case when @UseDate = 1 then Deals.DealDate
                                  when @UseDate = 2 then PaidDeals.PaidDate end) = datediff(dd, 0, getdate())

so that if the parameter @useDate  =1 it will compare based on the deal date, otherwise will compare with the paid date.. but this query takes like 30sec with the case when, but like 15sec with the case when (no matter if i use datediff(dd, 0, Deal.DealDate) or datediff(dd, 0,UpdateTable.Date)..

so is using dynamic sql my only choice ? or is there anyway to improve it ?

also im using this query in a update like i create a temp table with X dates depending on the selected range with 2 col (Date, TotalValue) and then run an update temptable set TotalValue =  queryabove does it matter also ?

does anyone have any ideia how i can improve it ?

Join our community to see this answer!
Unlock 1 Answer and 15 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 15 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros