Using Nested CASE Expressions in SQL Server

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:

Status Recommendation Report Output
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
Other None

Now that we have our problem, here’s an example of how to use a nested case expression to create a solution:

Using a Nested Case Expression
Using a Nested Case Expression

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:

  1. 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).
  2. 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.

Happy coding!


3 thoughts on “Using Nested CASE Expressions in SQL Server

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s