The IF, CASE, LOOP, WHILE, ITERATE, and LEAVE constructs are fully implemented.
These constructs may each contain either a single statement, or a block of statements using the BEGIN ... END compound statement. Constructs may be nested.
FOR loops are not currently supported.
IF search_condition THEN statement(s) [ELSEIF search_condition THEN statement(s)] ... [ELSE statement(s)] END IF
IF implements a basic conditional construct. If the search_condition evaluates to true, the corresponding SQL statement is executed. If no search_condition matches, the statement in the ELSE clause is executed.
Please note that there is also an IF() function. See Control flow functions.
CASE case_value WHEN when_value THEN statement [WHEN when_value THEN statement ...] [ELSE statement] END CASE
or
CASE WHEN search_condition THEN statement [WHEN search_condition THEN statement ...] [ELSE statement] END CASE
CASE implements a complex conditional construct. If a search_condition evaluates to true, the corresponding SQL statement is executed. If no search condition matches, the statement in the ELSE clause is executed.
Please note that the syntax of a CASE statement inside a stored procedure differs slightly from that of the SQL CASE expression. The CASE statement can not have an ELSE NULL clause, and the construct is terminated with END CASE instead of END. See Control flow functions.
[begin_label:] LOOP statement(s) END LOOP [end_label]
LOOP implements a simple loop construct, enabling repeated execution of a particular statement or group of statements. The statements within the loop are repeated until the loop is exited, usually this is accomplished with a LEAVE statement.
begin_label and end_label must be the same, if both are specified.
ITERATE label
ITERATE can only appear within LOOP, REPEAT, and WHILE statements. ITERATE means ``do the loop iteration again.''
For example:
CREATE PROCEDURE doiterate(p1 INT) BEGIN label1: LOOP SET p1 = p1 + 1; IF p1 < 10 THEN ITERATE label1; END IF; LEAVE label1; END LOOP label1; SET @x = p1; END
[begin_label:] REPEAT statement(s) UNTIL search_condition END REPEAT [end_label]
The statements within a REPEAT statement are repeated until the search_condition is true.
begin_label and end_label must be the same, if both are specified.
For example:
mysql> delimiter | mysql> CREATE PROCEDURE dorepeat(p1 INT) -> BEGIN -> SET @x = 0; -> REPEAT SET @x = @x + 1; UNTIL @x > p1 END REPEAT; -> END -> | Query OK, 0 rows affected (0.00 sec) mysql> CALL dorepeat(1000)| Query OK, 0 rows affected (0.00 sec) mysql> SELECT @x| +------+ | @x | +------+ | 1001 | +------+ 1 row in set (0.00 sec)
[begin_label:] WHILE search_condition DO statement(s) END WHILE [end_label]
The statements within a WHILE statement are repeated as long as the search_condition is true.
begin_label and end_label must be the same, if both are specified.
For example:
CREATE PROCEDURE dowhile() BEGIN DECLARE v1 INT DEFAULT 5; WHILE v1 > 0 DO ... SET v1 = v1 - 1; END WHILE; END