I'm currently writing an SQL Query, where a few of the columns returned need to be calculated depending on quite a lot of conditions.
I'm currently using nested case statements, but its getting messy. Is there a better (more organised and/or readable) way?
(I am using Microsoft SQL Server, 2005)
A simplified example:
SELECT
col1,
col2,
col3,
CASE
WHEN condition
THEN
CASE
WHEN condition1
THEN
CASE
WHEN condition2
THEN calculation1
ELSE calculation2
END
ELSE
CASE
WHEN condition2
THEN calculation3
ELSE calculation4
END
END
ELSE
CASE
WHEN condition1
THEN
CASE
WHEN condition2
THEN calculation5
ELSE calculation6
END
ELSE
CASE
WHEN condition2
THEN calculation7
ELSE calculation8
END
END
END AS 'calculatedcol1',
col4,
col5 -- etc
FROM table
You could try some sort of COALESCE trick, eg:
a user-defined function may server better, at least to hide the logic - esp. if you need to do this in more than one query
Here's a simple solution to the nested "Complex" case statment: --Nested Case Complex Expression
Just make sure you have an end statement for every case statement
I personally do it this way, keeping the embedded CASE expressions confined. I'd also put comments in to explain what is going on. If it is too complex, break it out into function.
Wrap all those cases into one.
I went through this and found all the answers super cool, however wants to add to answer given by @deejers
you can make ELSE optional as its not mandatory, it is very helpful in many scenarios.