Wednesday, June 24, 2009

(FAQ) How To Use SQL's SELECT CASE Statement

SQL provides a mechanism for returning different values in a SELECT clause based on Boolean conditions: the CASE statement. This statement resembles Visual Basics Select Case statement.

The SQL CASE statement has WHEN, THEN, and ELSE clauses along with an END terminator. The syntax is:

CASE [expression]
WHEN [value | Boolean expression] THEN [return value]
[ELSE [return value]]
END

Sample:
SELECT
CASE @TestVal
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 3 THEN 'Third'
ELSE 'Other'
END


No comments:

Post a Comment