Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

Professional Opinions
Ask a Question
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

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 ?

Avatar of Anthony Perkins
This problem has been solved!
Unlock 1 Answer and 15 Comments.
See Answers