SQL IF…ELSE Statement

Saturday, January 07, 2012

tags SQL

The SQL IF...ELSE Statement imposes conditions (boolean expression) on the execution of a Transact-SQL statement. The SQL statement(s) that follows an IF keyword is executed if the condition is satisfied (TRUE). The optional ELSE keyword will execute the SQL statement(s) that follow when the IF condition is not satisfied (FALSE). The IF...ELSE Statement is generally used in a SQL procedure or trigger.

Syntax



IF (expression)
BEGIN
Sql Code
...
END
ELSE
BEGIN
Sql Code
...
END


Example



IF @quantity > 0
BEGIN
SELECT [Name], [Qty]
FROM INVENTORY
WHERE InvID = @ID
END
ELSE
BEGIN
SELECT 'Not In Stock'
END

If one SQL statement follows the IF or ELSE block, the BEGIN and END keywords are optional.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

SQL Cookbook Head First SQL: Your Brain on SQL A Learners Guide