How do I use T-SQL's Case/When?

grady picture grady · Jul 27, 2010 · Viewed 124k times · Source

I have a huge query which uses case/when often. Now I have this SQL here, which does not work.

 (select case when xyz.something = 1
 then
     'SOMETEXT'
 else
      (select case when xyz.somethingelse = 1)
      then
          'SOMEOTHERTEXT'
      end) 

      (select case when xyz.somethingelseagain = 2)
      then
          'SOMEOTHERTEXTGOESHERE'
      end)
 end) [ColumnName],

Whats causing trouble is xyz.somethingelseagain = 2, it says it could not bind that expression. xyz is some alias for a table which is joined further down in the query. Whats wrong here? Removing one of the 2 case/whens corrects that, but I need both of them, probably even more cases.

Answer

Florian Reischl picture Florian Reischl · Jul 27, 2010
SELECT
   CASE 
   WHEN xyz.something = 1 THEN 'SOMETEXT'
   WHEN xyz.somethingelse = 1 THEN 'SOMEOTHERTEXT'
   WHEN xyz.somethingelseagain = 2 THEN 'SOMEOTHERTEXTGOESHERE'
   ELSE 'SOMETHING UNKNOWN'
   END AS ColumnName;