Note: This article is intended for developers who have a working knowledge of SQL Server’s CASE expression. If you do not, I reading this article from Microsoft; it gives a pretty good overview of the basics.
Applications are loaded with conditional logic. So it’s not a big surprise when you stumble across a scenario where one half of a conditional expression is the result of an entirely separate conditional expression. If you’re running into this on the backend of your application, then a nested case statement might be of use to you. Let’s take a look at a real world example.
Let’s say you’ve been asked to write a procedure to generate a report for a business unit within your company. Let’s assume that this unit has both a Status property and a Recommendation property, both of which are stored in the database and related through foreign keys. The requestor gives you the following matrix to use for determining what output to display on the report:
|In Production||Any||In Production|
|In Test||Add||Add to Production Queue|
|In Test||Remove||Return to Development Queue|
|In Test||Remain||Remain in Test Queue|
|In Development||Add||Add to Testing Queue|
|In Development||Remain||Remain in Development Queue|
Now that we have our problem, here’s an example of how to use a nested case expression to create a solution:
And there you have it. This example is pretty quick and dirty but it should give you a good grasp of the basic concepts needed to use this technique.
A couple quick additional tips:
- Do not attempt to derive a column name for any of the nested case statements as this will cause an error. If you wish to use a derived column name for the entire expression, do so at the end of the outermost case statement (as I have done in the example).
- You may nest deeper than two levels but, if you find the need arising, you may want to look at alternative approaches for maintainability’s sake before proceeding with a nesting nightmare.