T-SQL IF ELSE Statement – Microsoft SQL

SQL IF … ELSE Statement used to test a condition. IF… ELSE Statement using in execution of a Transact-SQL statement (Store Procedure or T-SQL) and Trigger.

IF tests can be nested after another IF or following an ELSE. There is no limit to the number of nested levels you can go.

IF condition is satisfied and the Boolean expression returns TRUE, it will executed IF Block SQL statement. IF condition is not satisfied and the Boolean expression returns FALSE, it will executed ELSE Block SQL Statement code.

Sample Syntax for IF…ELSE
IF ( Boolean_expression )
BEGIN
Sql Statement Block
END
ELSE
BEGIN
Sql Statement Block
END

Below is simple example of IF…ELSE Statement With 1 IF…ELSE Block
For Boolean_expression part, you can replace with your condition to match with your SQL query.
It also can using Exists in the Condition to check the existence of a SQL Statement or Row.

IF (3>2)
BEGIN
SELECT 'Correct'
END
ELSE
BEGIN
SELECT 'Wrong'
END

Value = Correct

IF (3<2)
BEGIN
SELECT 'Correct'
END
ELSE
BEGIN
SELECT 'Wrong'
END

Value = Wrong

Below is another Example of More than 1 IF…ELSE SQL Statement Block

IF (10<2)
SELECT 'Correct'
ELSE
SELECT 'Wrong'
IF ((10-2) > 5)
SELECT 'More Than 5'

Value = Wrong
Value = More Than 5

If your IF…ELSE Block SQL Statement only have 1 SQL query, you no need to include the BEGIN…END. If your IF…ELSE Block SQL Statement have more than 1 SQL query, you need to include the BEGIN…END to let it executed all the SQL Query in your SQL Query Block.

About onlinejt

Blogger

,

No comments yet.

Leave a Reply

*