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
The [expression] is optional and contains a table column or a variable. When you specify [expression] directly after the CASE, you must populate the [value] parameter in the WHEN clause:
DECLARE @TestVal int
SET @TestVal = 3
SELECT
CASE @TestVal
WHEN 1 THEN 'First'
WHEN 2 THEN 'Second'
WHEN 3 THEN 'Third'
ELSE 'Other'
END
Here is an example:-
Table Name: tbl_User
---------------
Name | Age |
---------------
User1 | 8 |
User2 | 10 |
User3 | 35 |
User4 | 50 |
---------------
SELECT
CASE Age
WHEN <=12 THEN 'Child'
WHEN <=18 THEN 'Teen'
ELSE 'Adult'
END AS 'Group'
FROM tbl_User
WHERE Name = 'User1'
Output:-
-------
Group |
-------
Child |
-------
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment