Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

IF ELSE Statement in SQL Server

The IF ELSE statement controls the flow of execution in SQL Server. It can be used in
stored-procedures, functions, triggers, etc. to execute the SQL statements based on the
specified conditions.

Syntax:

IF Boolean_expression
{ sql_statement | statement_block }
[ ELSE
{ sql_statement | statement_block } ]

Boolean_expression: A boolean expression that returns TRUE or FALSE. If the Boolean


expression contains a SELECT statement then it should be enclosed in parentheses.

sql_statement | statement_block: A single or multiple statements that need to be executed. To


include multiple statements, enclosed them between BEGIN and END keywords.

The ELSE block is optional. If the Boolean expression with the IF statement returns FALSE,
then the control is passed to the ELSE statement.

If the condition in the IF block returns TRUE, then the SQL statement block after the IF
statement is executed. If the condition returns FALSE, then the control executes the ELSE
block if present, or else it exits the IF statement.

Example 1
The following example demonstrates the if-else condition.

DECLARE @mySalary INT = 5000,


@avgSalary INT = 4000;

IF @mySalary > @avgSalary


PRINT 'My Salary is above the average salary.';
ELSE
PRINT 'My Salary is less than the average salary.';

In the above example, the IF condition @mySalary > @avgSalary checks whether the
@mySalary is greater than @avgSalary The @mySalary > @avgSalary returns TRUE, so the
statement below it will be executed.

Changing the value of any variable will affect the result, as shown below.
IF ELSE Statement with SELECT Query
The following example uses the SELECT query to demonstrate the IF ELSE condition.

Example: IF ELSE with SELECT Query


if (select AVG(Salary) from Employee) > 5000
print 'Average salary is greater than 5000';
else
print 'Average salary is less than 5000';

In the above example, the IF statement contains the select query in the parenthesis select
AVG(Salary) from Employee and checks whether it is greater than 5000 or not. The whole
condition is (select AVG(Salary) from Employee) > 5000. It displays the message
based on the return TRUE or FALSE.

Nested IF Statement
The following example demonstrates the nested IF statements.

DECLARE @StudentMarks INT = 85;

IF (@StudentMarks > 80)


BEGIN
IF @StudentMarks > 90
PRINT 'A+';
ELSE
PRINT 'A-';
END
ELSE
PRINT 'Below A grade'

In the above example, the first IF condition contains another IF ELSE condition in the block.
In the outer IF condition, the variable @StudentMarks is greater than 80 then it executes in
the second inner IF condition is checked, if it is greater than 90 then A+ is printed Else A- is
printed.
If @StudentMarks is less than 80 and the outer IF condition returns FALSE, then the message
'Below A grade' will be displayed.

CASE statement
The CASE statement has the functionality of an IF-THEN-ELSE statement. You can use the
CASE statement within a SQL statement.

Syntax

CASE expression
WHEN value_1 THEN result_1
WHEN value_2 THEN result_2
...
WHEN value_n THEN result_n
ELSE result
END

OR
CASE
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END

Example
SELECT contact_id,
CASE website_id
WHEN 1 THEN 'TechOnTheNet.com'
WHEN 2 THEN 'CheckYourMath.com'
ELSE 'BigActivities.com'
END
FROM contacts;

Example
SELECT contact_id,
CASE
WHEN website_id = 1 THEN 'TechOnTheNet.com'
WHEN website_id = 2 THEN 'CheckYourMath.com'
ELSE 'BigActivities.com'
END
FROM contacts;

One thing to note is that the ELSE condition within the CASE statement is optional.

SELECT contact_id,
CASE
WHEN website_id = 1 THEN 'TechOnTheNet.com'
WHEN website_id = 2 THEN 'CheckYourMath.com'
END
With the ELSE clause omitted, if no condition was found to be true, the CASE statement
would return NULL.

Loops in SQL Server


In SQL Server, a loop is the technique where a set of SQL statements are executed repeatedly
until a condition is met.

SQL Server supports the WHILE loop. The execution of the statements can be controlled
from within the WHLE block using BREAK and CONTINUE keywords.

Syntax:

WHILE <condition>
SQL Statement | statement_block | BREAK | CONTINUE

Boolean_expression : A boolean expression that returns TRUE or FALSE.

sql_statement | statement_block : A single or a group of SQL statements (statement block).


Statement block should be enclosed with BEGIN and END keywords.

BREAK: Causes the flow to exit from the innermost WHILE loop. Statements after the END
keyword are executed after the BREAK.

CONTINUE: Causes the WHILE loop to restart. It ignores all statements after the
CONTINUE keyword.

While Loop
The following example uses the WHILE loop to print numbers.

DECLARE @i INT = 10;

WHILE @i <= 30
BEGIN
PRINT (@i);
SET @i = @i + 10;
END;
In the above example, an integer variable @i is set to 10. The condition of the WHILE loop @i <= 30
indicates that it will execute the block until @i is 30. The block inside the WHILE loop is wrapped
within the BEGIN and END keywords. The variable @i is printed and then incremented with 10.

Nested Loops
The following example demonstrates the nested loop.

Example: Nested Loop

DECLARE @i INT = 10, @j INT = 1;

WHILE @i <= 30
BEGIN
PRINT CONCAT ('i = ', @i);

WHILE @j <=3
BEGIN
PRINT CONCAT ('j = ', @j);
SET @j = @j + 1;
END
SET @i = @i + 10;
END;

In the above example, two variables i and j are printed and incremented in two different WHILE
loops. The outer WHILE loop executes the variable i is less than or equal to 50. The inner loop is
executed for every run of the outer loop for the condition j <= 2.

Stored Procedure Parameters: Input,


Output, Optional
Here you will learn about stored procedure parameters, optional parameters, and executing
stored procedures with parameters in SQL Server.

 A stored procedure can have zero or more INPUT and OUTPUT parameters.
 A stored procedure can have a maximum of 2100 parameters specified.
 Each parameter is assigned a name, a data type, and direction like Input, Output, or
Return. If a direction is not specified, then by default, it is Input.
 You can specify a default value for the parameters.
 Stored procedures can return a value to the calling program if the parameter is
specified as OUTPUT.
 The parameter values must be a constant or a variable. It cannot be a function name.
 Parameter variables can be either user-defined or system variables like @spid

Stored Procedure with Input Parameters


Consider the following stored procedure example with the input parameters.
Example: Stored Procedure with INPUT Parameters:
CREATE PROCEDURE uspUpdateEmpSalary
(
@empId int
,@salary money
)
AS
BEGIN
UPDATE dbo.Employee
SET Salary = @salary
WHERE EmployeeID = @empId
END

In the above stored procedure uspUpdateEmpSalary, the @empId and @Salary are INPUT
parameters. By default, all the parameters are INPUT parameters in any stored procedure unless
suffix with OUTPUT keyword. @empId is of int type and @salary is of money data type. You pass
the INPUT parameters while executing a stored procedure, as shown below.

Example: Passing INPUT Parameters


EXECUTE dbo.uspUpdateEmpSalary @EmpId = 4, @Salary = 25000

-- or

EXEC dbo.uspUpdateEmpSalary 4, 25000

Parameter Names
 The stored procedure parameters names must start with a single @.
 The name must be unique in the scope of the stored procedure.
 If parameter values are passed as @Param1 = value1, @ Param2 = value2 as shown in the
above example, then the parameters can be passed in any order.
 If one parameter is supplied as @param1 = value, then all parameters must be supplied in
the same manner.

OUTPUT Parameters
The OUTPUT parameter is used when you want to return some value from the stored
procedure. The calling program must also use the OUTPUT keyword while executing the
procedure.

The following stored procedure contains INPUT and OUTPUT parameters.


Example: Stored Procedure with OUTPUT Parameter
CREATE PROCEDURE uspGetManagerID
@empId int,
@managerId int OUTPUT
AS
BEGIN
SELECT @managerId = ManagerID
FROM dbo.Employee
WHERE EmployeeID = @empId
END

In the above uspGetManagerID stored procedure, @manageId is an OUTPUT parameter. The value
will be assigned in the stored procedure and returned to the calling statement. The following pass
the OUTPUT parameter while executing the stored procedure.

Example: Passing OUTPUT Parameter


DECLARE @managerID int

EXECUTE uspGetManagerID @empId = 10045, @managerId OUTPUT

PRINT @managerId

Above, the uspGetManagerID is called by passing INPUT parameter @employeeID = 2 and


@managerID OUTPUT as the output parameter. Notice that we have not assigned any value to
an OUTPUT variable @managerID and also specified the OUTPUT keyword.

There are a total of three methods of returning data from a stored procedure: OUTPUT
parameter, result sets, and return codes.

Result sets: If the body of the stored procedure has a SELECT statement, then the rows
returned by the select statement are directly returned to the client.

Return code: A stored procedure can return an integer value called the Return code which
will indicate the execution status of the procedure. You specify the return code using the
RETURN keyword in the procedure.

Optional Parameters
SQL Server allows you to specify the default values for parameters. It allows you to skip the
parameters that have default values when calling a stored procedure.

The default value is used when no value is passed to the parameter or when the DEFAULT
keyword is specified as the value in the procedure call.

Specify the default value when you declare parameters, as shown below.
Example: Stored Procedure with Optional Parameter

CREATE PROCEDURE uspUpdateEmpSalary


(
@empId int
,@salary money = 1000
)
AS
BEGIN
UPDATE dbo.Employee
SET Salary = @salary
WHERE EmployeeID = @empId
END

Above, @empsalary money = 0 declares @salary parameter and assigns the default value.
Now, you can call the above procedure without passing @salary parameter, as shown below.

Example: Calling Stored Procedure

EXEC uspUpdateEmpSalary 4

The above statement will update the Salary column with the default value 1000 for the
EmployeeID 4. Thus, making @salary parameter as optional.

You might also like