Quantcast
Viewing all articles
Browse latest Browse all 4

ELSE IF vs. just plain ELSE

This is little bit confusing.

T-SQL does not have ELSE IF branch, and instead it seems that uses nested if-s. So For example, what seems like ELSE IF branches like this

DECLARE @a int = 12;

IF (@a > 0 AND @a < 4) 
	PRINT 'Less then 4'
ELSE IF (@a >= 3 AND @a < 8) 
	PRINT 'Between 3 and 8'
ELSE IF (@a >= 5 AND @a < 12)
	PRINT 'Between 5 and 12'
ELSE 
	PRINT '12 or more'

It seems to be interpreted like this:

DECLARE @a int = 12;

IF (@a > 0 AND @a < 4) 
	PRINT 'Less then 4'
ELSE
	IF (@a >= 3 AND @a < 8) 
		PRINT 'Between 3 and 8'
	ELSE 
		IF (@a >= 5 AND @a < 12)
			PRINT 'Between 5 and 12'
		ELSE 
			PRINT '12 or more'

Compiler interprete this like nested IF statements.

But this is semanticaly same as ELSE IF statement, because T-SQL treates IF...ELSE like block statement, so it is very interesting that you got 2 conditions validated to TRUE. It seems not possible, so please give us an example.

In books online there is suggestion that you explicitly enclose statement block with BEGIN ... END, and alos that you use line terminators (;). It is good suggestion in my opinion. This is an example of such code.

DECLARE @a int = 12;

IF (@a > 0 AND @a < 4) 
BEGIN
	PRINT 'Less then 4';
END;
ELSE
BEGIN
	IF (@a >= 3 AND @a < 8) 
	BEGIN
		PRINT 'Between 3 and 8';
	END;
	ELSE
	BEGIN 
		IF (@a >= 5 AND @a < 12)
		BEGIN
			PRINT 'Between 5 and 12';
		END;
		ELSE
		BEGIN 
			PRINT '12 or more';
		END;
	END;
END;

This is excrept from books online:

"Is any valid Transact-SQL statement or statement grouping as defined with a statement block. To define a statement block (batch), use the control-of-flow language keywords BEGIN and END. Although all Transact-SQL statements are valid within a BEGIN...END block, certain Transact-SQL statements should not be grouped together within the same batch (statement block)."


if (helpful) then Vote();



Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>