In this post explains how to use the SQL Server (Transact-SQL) CASE statement with syntax and examples.
In SQL Server (Transact-SQL), the CASE statement has the functionality of an IF-THEN-ELSE statement. You can use the CASE statement within a SQL statement.
The syntax for the CASE statement in SQL Server (Transact-SQL) is:
OR
The expression that will be compared to each of the values provided. (ie: value_1, value_2, ... value_n).
The values that will be used in the evaluation. Values are evaluated in the order listed. Once a value matches expression, the CASE statement will execute the corresponding statements and not evaluate any further.
The conditions that will be evaluated. Conditions are evaluated in the order listed. Once a condition is found to be true, the CASE statement will return the result and not evaluate the conditions any further. All conditions must be the same datatype.
The value returned once a condition is found to be true. All values must be the same datatype.
The CASE statement can be used in the following versions of SQL Server (Transact-SQL):
The CASE statement can be used in SQL Server (Transact-SQL).
You could use the CASE statement in a SQL statement as follows: (includes the expression clause)
Or you could write the SQL statement using the CASE statement like this: (omits the expression clause)
One thing to note is that the ELSE condition within the CASE statement is optional. It could have been omitted. Let's modify our examples with the ELSE condition omitted.
Your SQL statement would look as follows:
OR
With the ELSE clause omitted, if no condition was found to be true, the CASE statement would return NULL.
Here is an example that demonstrates how to use the CASE statement to compare different conditions:
Just remember that conditions are evaluated in the order listed. Once a condition is found to be true, the CASE statement will return the result and not evaluate the conditions any further. So be careful when choosing the order that you list your conditions.