How can I SELECT multiple columns within a CASE WHEN on SQL Server? How can I SELECT multiple columns within a CASE WHEN on SQL Server? sql-server sql-server

How can I SELECT multiple columns within a CASE WHEN on SQL Server?


The problem is that the CASE statement won't work in the way you're trying to use it. You can only use it to switch the value of one field in a query. If I understand what you're trying to do, you might need this:

SELECT    ActivityID,   FieldName = CASE                   WHEN ActivityTypeID <> 2 THEN                      (Some Aggregate Sub Query)                  ELSE                     (Some Aggregate Sub Query with diff result)               END,   FieldName2 = CASE                  WHEN ActivityTypeID <> 2 THEN                      (Some Aggregate Sub Query)                  ELSE                     (Some Aggregate Sub Query with diff result)               END


No, CASE is a function, and can only return a single value. I think you are going to have to duplicate your CASE logic.

The other option would be to wrap the whole query with an IF and have two separate queries to return results. Without seeing the rest of the query, it's hard to say if that would work for you.


"Case" can return single value only, but you can use complex type:

create type foo as (a int, b text);select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;