Using the CASE Statement in SQL Server
The T-SQL CASE Statement fundamentals
What is CASE in SQL?SQL CASE statement evaluates a condition and returns a result that meets that condition. If none of the conditions is evaluated to TRUE it returns a value from the ELSE block. In simple words, the CASE expression is the way to build the IF - THEN logic into SQL.
A quick review of CASE rules- CASE must be followed by at least one WHEN... THEN expression
- Every CASE statement must end with the END keyword
- The ELSE argument is optional
- CASE can be used in any statement or clause that allows a valid expression
- Only 10 levels of nesting are allowed in SQL Server
The syntax for the SELECT statement with a simple CASE expression is as follows:
SELECT CASE expression WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE result END