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:
CASE case_value
WHEN when_value THEN statement_list
[WHEN when_value THEN statement_list] ...
[ELSE statement_list]
ENDIf we want to test other type of conditions:
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
ENDHere is a example for the second usage:
SELECT OrderID, Quantity,
CASE
WHEN Quantity > 30 THEN "The quantity is greater than 30"
WHEN Quantity = 30 THEN "The quantity is 30"
ELSE "The quantity is something else"
END
FROM OrderDetails;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
LOOPimplements 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 aLEAVEstatement. Within a stored function,RETURNcan also be used, which exits the function entirely.
Neglecting to include a loop-termination statement results in an infinite loop.
ALOOPstatement can be labeled.
Example:
WHILE Syntax
The statement list within aWHILEstatement 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.
AWHILEstatement can be labeled.
Example:
REPEAT Syntax
The statement list within aREPEATstatement is repeated until thesearch_condition_expression is true. Thus, aREPEATalways enters the loop at least once.statement_list_consists of one or more statements, each terminated by a semicolon (;) statement delimiter.
AREPEATstatement can be labeled.
Example:
RETURN Syntax
TheRETURNstatement terminates execution of a stored function and returns the value_expr_to the function caller. There must be at least oneRETURNstatement 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. TheLEAVEstatement can be used to exit a stored program of those types.
ITERATE Syntax
ITERATEcan appear only withinLOOP,REPEAT, andWHILEstatements.ITERATEmeans “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,LEAVEexits the program.
LEAVEcan be used withinBEGIN ... ENDor loop constructs (LOOP,REPEAT,WHILE).
Last updated
Was this helpful?