SQL Case evaluates a list of conditions and returns one possible result expressions.
CASE has two formats:
1. Simple CASE Function – Compares an expression to determine the result.
2. Searched CASE Function – Evaluates a set of Boolean expressions to determine the result.
Sample CASE Syntax
1. Simple CASE function:
CASE input_expression
WHEN when_expression THEN Result
ELSE result_expression
END
2. Searched CASE function:
CASE
WHEN Boolean_expression THEN Result
ELSE result_expression
END
1. Simple CASE Function
Evaluates input_expression and find the match with when_expression. If found, it will return the Result and if not found, it will return the ELSE result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.
DECLARE @Type varchar(20)
SET @Type = ‘Programming’
SELECT
CASE @Type
WHEN ‘Sql’ THEN ‘SQL Language’
WHEN ‘Programming’ THEN ‘How2Assist.com’
WHEN ‘Travel’ THEN ‘TravelToHawaii’
ELSE ‘Not yet categorized’
END
Return Value = How2Assist.com
If SET @Type = ‘Picture’, then Return value = Not yet categorized
2.Searched CASE Function
Evaluates Boolean_expression for each WHEN clause and returns result_expression of the first Boolean_expression that evaluates to TRUE.
If no Boolean_expression evaluates to TRUE, SQL Server returns the ELSE result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.
DECLARE @Price integer
SET @Price = (20-9)
SELECT
CASE
WHEN @Price IS NULL THEN ‘Not yet priced’
WHEN @Price < 10 THEN ‘Very Reasonable Price’
WHEN @Price >= 10 AND @Price < 20 THEN ‘OK Price’
ELSE ‘Expensive book!’
END
Value = OK Price
If SET @Price = (30-1), then return Value = Expensive book!