Simple LOOP : LOOP « Procedure Function « MySQL Tutorial






[begin_label:] LOOP
    statement_list
END LOOP [end_label]

A LOOP statement can be labeled.

end_label cannot be given unless begin_label also is present.

If both are present, they must be the same.

mysql>
mysql> delimiter $$
mysql> CREATE PROCEDURE myProc()
    -> DETERMINISTIC
    -> BEGIN
    ->   DECLARE counter INT DEFAULT 0;
    ->
    ->   simple_loop: LOOP
    ->     SET counter=counter+1;
    ->     select counter;
    ->     IF counter=10 THEN
    ->        LEAVE simple_loop;
    ->     END IF;
    ->   END LOOP simple_loop;
    ->   SELECT 'I can count to 10';
    -> END$$
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql> delimiter ;
mysql>
mysql> call myProc();
+---------+
| counter |
+---------+
|       1 |
+---------+
1 row in set (0.00 sec)

+---------+
| counter |
+---------+
|       2 |
+---------+
1 row in set (0.02 sec)

+---------+
| counter |
+---------+
|       3 |
+---------+
1 row in set (0.02 sec)

+---------+
| counter |
+---------+
|       4 |
+---------+
1 row in set (0.02 sec)

+---------+
| counter |
+---------+
|       5 |
+---------+
1 row in set (0.02 sec)

+---------+
| counter |
+---------+
|       6 |
+---------+
1 row in set (0.02 sec)

+---------+
| counter |
+---------+
|       7 |
+---------+
1 row in set (0.02 sec)

+---------+
| counter |
+---------+
|       8 |
+---------+
1 row in set (0.02 sec)

+---------+
| counter |
+---------+
|       9 |
+---------+
1 row in set (0.33 sec)

+---------+
| counter |
+---------+
|      10 |
+---------+
1 row in set (0.33 sec)

+-------------------+
| I can count to 10 |
+-------------------+
| I can count to 10 |
+-------------------+
1 row in set (0.33 sec)

Query OK, 0 rows affected (0.33 sec)

mysql>
mysql> DROP PROCEDURE myProc;
Query OK, 0 rows affected (0.00 sec)

mysql>
mysql>








11.18.LOOP
11.18.1.Simple LOOP
11.18.2.Nesting if statement with LOOP statement
11.18.3.LOOP with LEAVE
11.18.4.LOOP with ITERATE
11.18.5.LOOP Statement with LEAVE