IF-ELSE statement represents a control statement that executes a set of blocks. If the condition specified in the IF block is met (TRUE), then the sql code from the IF block is executed (the IF block is executed), if the condition is not met (FALSE), then the ELSE block is executed. An IF-ESLE block starts with checking the IF condition and ends with ELSE when the IF condition is not met.
Syntax
IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]
IF
In this first example, we will show how to use an IF-ELSE statement, the condition of IF being TRUE, the result YES will be displayed.
USE model
GO
BEGIN
IF EXISTS(SELECT id FROM students WHERE name = 'Jennifer')
PRINT 'YES'
ELSE
PRINT 'NO'
END
GO
ELSE
In the second example, it is checked if the condition of IF statement is TRUE, the condition is FALSE, and the ELSE block will be executed.
USE model
GO
DECLARE @id int;
SET @id = 0;
BEGIN
IF @id=1
PRINT 'YES'
ELSE
PRINT 'NO'
END
GO