Why CASE statement in Where clause for MS Sql server -
doing performance tuning on 3rd party vendor system in ms sql server 2012.
they lot of clauses this:
where ( case when @searchid = '' 1 when ((c.sapcustomernumber = @searchid ) or (c.sapcustomernumber = @sapid)) 1 else 0 end = 1 )
other confusing query plan, advantage if there case 1 or 0 in clause?
thanks
the common, far, cause sort of code appear new sql, case
expressions or both. somehow become fixated on case
, decide should used conditional evaluations.
this mistake , can replaced simpler boolean logical, @bogdan suggested in comments:
((c.sapcustomernumber = @searchid ) or (c.sapcustomernumber = @sapid) or (@searchid = '' ))
the second reason can done if attempting enforce order of evaluation of predicates1. case
documented evaluate when
conditions in order (provided scalar expressions, not aggregates). i'd not recommend writes code though - it's mistaken first form instead. , if particular evaluation order best today, today's data, who's whether still correct tomorrow, or in month or years time?
1sql not guarantee evaluation order where
clause predicates in general, nor form of short-circuiting evaluation. optimizer free re-order predicates - both within where
clause , in join
/on
clauses - try achieve overall result cheaply possible. shouldn't, generally, try prevent doing so.
if it's not picking efficient plan, far better fixed updating/creating indexes , statistics or forcing specific plan, rather using case
.
Comments
Post a Comment