Friday, November 25, 2011

SQL IF...ELSE Statement

SQL IF...ELSE Statement used to test a condition.

IF tests can be nested after another IF or following an ELSE. There is no limit to the number of nested levels.
Syntax for IF...ELSEIF ( Boolean_expression )
BEGIN
Sql Statement Block
END
ELSE
BEGIN
Sql Statement Block
END


eX:-

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.

No comments:

Post a Comment

SAP HANA Cloud Integration SAP : Part -01

What Is SAP HANA Cloud Integration? CPI-DS is a cloud-based data integration tool for batch & scheduled data integration between on-pr...