Professional Documents
Culture Documents
Conditional Constructs Procedure
Conditional Constructs Procedure
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 } ]
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.
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.
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.
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.
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
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.
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.
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.
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
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.
-- or
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.
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.
PRINT @managerId
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
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.
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.