Simple LOOP : LOOP « Procedure Function « SQL / MySQL






Simple LOOP

  
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>

          
  








Related examples in the same category

1.Nesting if statement with LOOP statement
2.LOOP with LEAVE
3.LOOP with ITERATE
4.LOOP Statement with LEAVE
5.Loop with label