In T-SQL, an IF-ELSE IF-ELSE block is ended implicitly by the next statement or the end of the batch, as T-SQL does not require a special END
keyword to close the IF
block in the same way some other programming languages do.
Here’s a basic structure of an IF-ELSE IF-ELSE
block in T-SQL:
Syntax:
IF condition1
BEGIN
-- SQL statements for condition1
END
ELSE IF condition2
BEGIN
-- SQL statements for condition2
END
ELSE
BEGIN
-- SQL statements for the ELSE case
END
Example:
DECLARE @value INT = 10;
IF @value > 15
BEGIN
PRINT 'Value is greater than 15';
END
ELSE IF @value = 10
BEGIN
PRINT 'Value is equal to 10';
END
ELSE
BEGIN
PRINT 'Value is less than 10';
END
Key Points:
IF
: Executes a block of code if the condition is true.ELSE IF
: Executes a block of code if the previousIF
condition was false and this condition is true.ELSE
: Executes a block of code if none of the previous conditions were true.- Each block of code inside the
BEGIN ... END
is optional, depending on whether you need multiple statements inside the condition. - The
END
keyword is used to close theBEGIN ... END
block for each condition but not to close the entireIF-ELSE
block itself.
Important Note:
- T-SQL allows you to group multiple statements under a condition using
BEGIN
andEND
, but if you only have a single statement, theBEGIN
andEND
are not required. - The
END
is only needed to group multiple statements inside aBEGIN ... END
block.
Example without BEGIN ... END
(single statement):
IF @value > 15
PRINT 'Value is greater than 15';
ELSE IF @value = 10
PRINT 'Value is equal to 10';
ELSE
PRINT 'Value is less than 10';
In this case, no BEGIN
or END
is required because each block contains just one statement.