Skip to main content

LOOP

The LOOP statement is used to construct simple loops.

[begin_label:] LOOP
statement_list
END LOOP [end_label]

The LOOP statement allows you to repeatedly execute the statement_list, which consists of one or more statements, each ending with a semicolon (;). The statements within the loop will continue to execute until the loop is terminated using the LEAVE statement. In stored functions, you can also use RETURN to exit the function completely. If no loop termination statement is included, it will result in an infinite loop. You can use label to mark the LOOP statement.

Here is an example of a LOOP statement:

DELIMITER //

CREATE PROCEDURE iter_proc(p1 INT)
BEGIN
loop_label1: LOOP
SET p1 = p1 + 10;
IF p1 < 100 THEN
ITERATE loop_label1;
END IF;
LEAVE loop_label1;
END LOOP loop_label1;
SET @x = p1;
END //
Query OK, 0 rows affected