Control Flow Statements
CASE syntax
When we need to react differently in different conditions, we use CASE
syntax. Here are two typical usages.
If we only need to test equality:
If we want to test other type of conditions:
Here is a example for the second usage:
CASE WHEN
is usually used in SELECT
statement, but it's possible to be used in other statements. Here is a example:
IF Syntax
IF
statement works similar to CASE WHEN
. In practice, we use CASE WHEN
more often.
LOOP Syntax
LOOP
implements a simple loop construct, enabling repeated execution of the statement list, which consists of one or more statements, each terminated by a semicolon (;
) statement delimiter. The statements within the loop are repeated until the loop is terminated. Usually, this is accomplished with aLEAVE
statement. Within a stored function,RETURN
can also be used, which exits the function entirely.
Neglecting to include a loop-termination statement results in an infinite loop.
ALOOP
statement can be labeled.
Example:
WHILE Syntax
The statement list within aWHILE
statement is repeated as long as thesearch_condition
_expression is true.statement_list
_consists of one or more SQL statements, each terminated by a semicolon (;
) statement delimiter.
AWHILE
statement can be labeled.
Example:
REPEAT Syntax
The statement list within aREPEAT
statement is repeated until thesearch_condition
_expression is true. Thus, aREPEAT
always enters the loop at least once.statement_list
_consists of one or more statements, each terminated by a semicolon (;
) statement delimiter.
AREPEAT
statement can be labeled.
Example:
RETURN Syntax
TheRETURN
statement terminates execution of a stored function and returns the value_expr
_to the function caller. There must be at least oneRETURN
statement in a stored function. There may be more than one if the function has multiple exit points.
This statement is not used in stored procedures, triggers, or events. TheLEAVE
statement can be used to exit a stored program of those types.
ITERATE Syntax
ITERATE
can appear only withinLOOP
,REPEAT
, andWHILE
statements.ITERATE
means “start the loop again.”
LEAVE Syntax
This statement is used to exit the flow control construct that has the given label. If the label is for the outermost stored program block,LEAVE
exits the program.
LEAVE
can be used withinBEGIN ... END
or loop constructs (LOOP
,REPEAT
,WHILE
).
Last updated