MySQL WHILE Loop: Syntax & Usage Guide
The WHILE loop statement in MySQL is used to repeatedly execute a set of statements as long as a specific condition is met, until the condition is no longer satisfied. Here is a basic example:
SET @i = 0;
WHILE @i < 10 DO
SELECT @i;
SET @i = @i + 1;
END WHILE;
In the example above, the variable @i is first initialized to 0, followed by the definition of a WHILE loop that repeats the statements SELECT @i and SET @i = @i + 1 as long as the value of @i is less than 10. The loop ends when the value of @i reaches 10.
It is worth noting that the WHILE loop statement in MySQL can only be used within a stored procedure or function, and cannot be used in regular SQL queries. If you want to use a WHILE loop, you will need to first create a stored procedure or function to encapsulate the loop logic.