views:

138

answers:

2

Is there a way to use one CASE statement and return 2 different values?

Following query has 2 CASE statements with same conditions.

select case when DA.value = 1 
   then da.Good else da.Bad end as Foo,
  case when DA.value = 1 
   then ot.Good else ot.Bad end as Bar,
from someTable DA (nolock)
  join otherTable OT (nolock) on OT...
where ...

Is there anyway, to specify that CASE statement once?
so that there is no need to keep both CASE statements in sync whenever the condition changes?

+2  A: 

There's no way to do what you're describing. Not only is your case statement different for both cases, but you're returning values from totally different tables in each case.

Joseph
@Josheph. Thank you for the answer. This question was mainly to confirm whether there is actually a way to do so. But I was not able to find a way around it even after reading MSDN BOL.
Sung Meister
+2  A: 

Not sure if this is what you need, but you can do combinations like:

select
   case
      when da.value = 1 and ot.attributeValue = 1 then ot.good
      when da.value = 2 and ot.attributeValue = 3 then ot.good
      ...
      else ot.bad
   end Result
from
   someTable DA

   JOIN otherTable OT
      on (ot.id = da.id)

Ron

Ron Savage