Nested CASE Statement in T-SQL

22. July 2010

I always take for granite the usuability of the CASE statement in T-SQL. It is so useful and I should be using it more often.

For example I was working on a query the other day and of course I ended up using a CASE statement. The CASE statement is so flexible.

The example below is showing a nested CASE Statement in T-SQL:

CASE 
   WHEN @YourValue = CAST(ColumnName1 AS INT) 
	THEN CASE ColumnName1_1
		WHEN 1 THEN 'Yes'
		WHEN 0 THEN 'No'
		ELSE ''
	     END
   WHEN @YourValue = CAST(ColumnName2 AS INT) 
	THEN CASE ColumnName2_1
		WHEN 1 THEN 'Yes'
		WHEN 0 THEN 'No'
		ELSE ''
             END
   ELSE ''
END AS 'YourColumnName'

This proved to be very useful because I was taking the value of @YourValue and needed to see what value it matched against 2 seperate columns in the database.

If there was a match, I then wanted to do a nested CASE and see what value of another column was. In this example, you can see I just needed to output a Yes, No or blank.

Anyway, I just wanted to post this real quick to remind myself, and others to stick to simple concepts :)

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

Microsoft SQL

blog comments powered by Disqus