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?
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.
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.
Multiple conditions in CASE statementYou can evaluate multiple conditions in the CASE statement.
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 ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With