The SQL Server CASE statement is a conditional statement that returns a single value based on the evaluation of a statement. CASE expressions can be used in SQL anywhere an expression can be used like SELECT list, WHERE clause, HAVING clause, IN list, DELETE and UPDATE statements. CASE statement can also be nested. This provides a lot of pliability for evaluating multiple expressions.

SQL Case statement can be used in 2 forms:

1.       SQL CASE statement with simple expression to compare and get results.

2.       SQL CASE statement with search or comparison expression to get results.

· SQL CASE statement with simple expression to compare and get results

A simple CASE expression operates by comparing the first expression to the expression in each WHEN clause for equivalency.

Syntax

CASE expression
WHEN expression1 THEN expression1
[[WHEN expression2 THEN expression2] [...]]
[ELSE expressionN]
END

Example


SELECT CASE [Section] 
      WHEN 1 THEN 'One'
      WHEN 2 THEN 'Two'
      WHEN 3 THEN 'Three'
      WHEN 4 THEN 'Four'
      WHEN 5 THEN 'Five'
      ELSE 'Greater than Five'
END as [Sec_Word] FROM [Table_Test]

·SQL CASE statement with search or comparison expression to get

results

A search or comparison CASE expression allows comparison operators, and the use of AND and/or OR between each Boolean expression.

Syntax


 CASE
WHEN Boolean_expression1 THEN expression1
[[WHEN Boolean_expression2 THEN expression2] [...]]
[ELSE expressionN]
END

Example

SELECT CASE  
      WHEN [Section] < 5 THEN 'Less than Five'
      WHEN [Section] = 5 THEN 'Equal to Five'
      WHEN [Section] > 5 THEN 'Greater than Five'
END as [Sec_Word] FROM [Table_Test]
  Modified On Sep-18-2014 01:24:01 PM
  1. Thanks for sharing informative post.

    Your words increase my knowledge for sure. Thanks

Leave Comment