Monday, 29 October 2012

Case statement in sql server?


SQL SERVER – CASE Statement/Expression Examples and Explanation

CASE expressions can be used in SQL anywhere an expression can be used. Example of where CASE expressions can be used include in the SELECT list, WHERE clauses, HAVING clauses, IN lists, DELETE and UPDATE statements, and inside of built-in functions.
Two basic formulations for CASE expression 
1) Simple CASE expressions 
A simple CASE expression checks one expression against multiple values. Within a SELECT statement, a simple CASE expression allows only an equality check; no other comparisons are made. A simple CASE expression operates by comparing the first expression to the expression in each WHEN clause for equivalency. If these expressions are equivalent, the expression in the THEN clause will be returned.
Syntax:
CASE expressionWHEN expression1 THEN expression1
[[WHEN expression2 THEN expression2] [...]]
[ELSE expressionN]
END

Example:
DECLARE @TestVal INT
SET 
@TestVal 3SELECTCASE @TestValWHEN THEN 'First'WHEN THEN 'Second'WHEN THEN 'Third'ELSE 'Other'END


2) Searched CASE expressions

A searched CASE expression allows comparison operators, and the use of AND and/or OR between each Boolean expression. The simple CASE expression checks only for equivalent values and can not contain Boolean expressions. The basic syntax for a searched CASE expressions is shown below:
Syntax:
CASEWHEN Boolean_expression1 THEN expression1
[[WHEN Boolean_expression2 THEN expression2] [...]]
[ELSE expressionN]
END

Example:
DECLARE @TestVal INT
SET 
@TestVal 5SELECTCASEWHEN @TestVal <=THEN 'Top 3'ELSE 'Other'END

No comments:

Post a Comment