WHILE Statement : While « Procedure Function « MySQL Tutorial






The WHILE statement is another mechanism to loop over a set of statements until a condition is true.

[begin_label:] WHILE search_condition DO
    statement_list
END WHILE [end_label]
mysql>
mysql>
mysql> DELIMITER //
mysql> CREATE FUNCTION myFunction (quantity INT(10)) RETURNS INT(10)
    -> BEGIN
    ->
    ->     WHILE quantity MOD 12 > 0 DO
    ->     SET quantity = quantity + 1;
    ->     END WHILE;
    ->
    ->     RETURN quantity;
    ->
    -> END
    -> //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;
mysql>
mysql> select myFunction(10);
+----------------+
| myFunction(10) |
+----------------+
|             12 |
+----------------+
1 row in set (0.00 sec)

mysql>
mysql> select myFunction(24);
+----------------+
| myFunction(24) |
+----------------+
|             24 |
+----------------+
1 row in set (0.00 sec)

mysql>
mysql>
mysql> drop function myFunction;
Query OK, 0 rows affected (0.00 sec)

mysql>








11.14.While
11.14.1.WHILE Statement
11.14.2.While loop
11.14.3.IF statement in a While loop