Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to return multiple columns using 1 case statement?

I have 4 case statements that are exactly the same CASE criteria, but they all have different THEN/ELSE statements.

Is it possible to do this all in one, or do I need to separate these all out and copy and paste the code multiple times?

,CASE WHEN lm.Id IN ('1','2','3') THEN lm.name ELSE lm.Desc END AS [Column1]
,CASE WHEN lm.Id IN ('1','2','3') THEN '3' ELSE '1' END AS [Column2]
,CASE WHEN lm.Id IN ('1','2','3') THEN 'True' ELSE 'False' END AS [Column3]

Is it possible to do this with less code?

like image 609
mameesh Avatar asked Jun 27 '11 20:06

mameesh


People also ask

Can a CASE statement return multiple values?

It can only return one value. If you want the case expression to cover several return columns at once, you will have to write separate case expressions for each column.

Can we use two columns in CASE statement in SQL?

A CASE expression returns *one* value. If you, say, want to return two columns, each based on some condition, then you need to use two CASE expressions. Yes, you can evaluate different columns in the CASE statement.

Can you have multiple conditions in a CASE statement?

Multiple conditions in CASE statementYou can evaluate multiple conditions in the CASE statement.

Can CASE statement return multiple values in Oracle?

A CASE statement cannot return more than one value, it is a function working on one value. But this will probably be quite some work for the optimizer ...


1 Answers

I don't think this is possible in strict SQL. Some DB engines may support it as an extension. You could probably accomplish functionally the same thing through some other mechanism, though... possibly with a JOIN, or a UNION.

like image 199
Flimzy Avatar answered Oct 05 '22 23:10

Flimzy