Faculty of Computing and Informatics
Lesson 4 - Theory
Control Structures
Learning Objectives
After studying this lesson, you should be able to:
• Identify the uses and types of control structures
• Construct an IF statement
• Use CASE statements and CASE expressions
• Construct and identify different loop statements
Introduction
• Based on your current exposure, please give by example (either
using a scenario or any form to explain the importance of using
control structures in SQL server).
• Probably the most useful (and important) part of SQL
• You can manipulate SQL data in a very flexible and powerful way
Control Flow of Execution
IF-THEN
• IF-THEN statements are the simplest form of IF.
• The statements between THEN and END IF will be executed if
the condition is true. Otherwise, they are skipped.
IF-THEN-ELSE
• IF-THEN-ELSE statements add to IF-THEN by letting you specify
an alternative set of statements that should be executed if the
condition evaluates to FALSE.
IF-THEN-ELSIF-ELSE
• IF-THEN-ELSIF-ELSE provides a more convenient method of
checking many alternatives in one statement.
• Formally it is equivalent to nested IF-THEN-ELSE-IF-THEN
commands, but only one END IF is needed.
Loops
• With the LOOP, EXIT, WHILE and FOR statements, you can
arrange for your SQL function to repeat a series of commands.
• LOOP defines an unconditional loop that is repeated
indefinitely until terminated by an EXIT or RETURN
statement.
• The optional label can be used by EXIT statements in
nested loops to specify which level of nesting should be
terminated.
WHILE
• The WHILE statement repeats a sequence of statements so
long as the condition expression evaluates to true.
• The condition is checked just before each entry to the loop
body.
FOR (integer for-loop)
• This form of FOR creates a loop that iterates over a range of
integer values.
• The variable name is automatically defined as type integer
and exists only inside the loop.
• The two expressions giving the lower and upper bound of the
range are evaluated once when entering the loop.
• The iteration step is normally 1, but is -1 when REVERSE is
specified.