This tutorial explains how to use the WHILE statement (WHILE LOOP) in MySQL with syntax and examples.
In MySQL, the WHILE statement is used when you are not sure how many times you will execute the loop body and the loop body may not execute even once.
The syntax for the WHILE statement in MySQL is:
[ label_name: ] WHILE condition DO
{...statements...}
END WHILE [ label_name ];
Optional. It is a name associated with the WHILE loop.
Te condition is test each pass through the WHILE loop. If the condition evaluates to TRUE, the loop body is executed. If the condition evaluates to FALSE, the WHILE loop is terminated.
The statements of code to execute each pass through the WHILE loop.
Let's look at an example that shows how to use the WHILE statement in MySQL:
DELIMITER //
CREATE FUNCTION CalcIncome ( starting_value INT )
RETURNS INT
BEGIN
DECLARE income INT;
SET income = 0;
label1: WHILE income = 3000 DO
SET income = income + starting_value;
END WHILE label1;
RETURN income;
END; //
DELIMITER ;
In this WHILE LOOP example, the loop would terminate once income exceeded 3000 as specified by:
label1: WHILE income = 3000 DO
The WHILE LOOP will continue while income = 3000. And once income is > 3000, the loop will terminate.