Nested Case Statements in SQL

Need to do nested Case statements in SQL? Use the following syntax. This should result in ‘a1b1 – yar’

DECLARE @a INT
DECLARE @b INT

SET @a = 1
SET @b = 2

SELECT 
CASE
	WHEN @a = 1 THEN 
	CASE 
		WHEN @b = 1 THEN 'a1b1'
		WHEN @b = 2 THEN 'a1b2 - yar'
	END --Ends the inner case
	WHEN @a = 2 THEN 
	CASE
		WHEN @b = 1 THEN 'a2b1'
		WHEN @b = 2 THEN 'a2b2'
	END --Ends the inner case
END --Ends the outer case

This took me a little time to work out the syntax, but pretty simple once I understood case statements a little better.

For some more info on case statements, you can go to the msdn  article located at http://msdn.microsoft.com/en-us/library/ms181765.aspx

Jacob Saylor

Software developer in Kentucky

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: