ITERATE and LEAVE - Statements to Break Loops

This section describes ITERATE and LEAVE Statements used in stored procedures to break execution loops.

To break out of the current iteration and continue with the next iteration of a LOOP, REPEAT or WHILE statement, you can use the ITERATE statement:

label WHILE condition
   ......
   ITERATE label; 
   ......
END WHILE label

To break out of the current iteration and leave the LOOP, REPEAT or WHILE statement, you can use the LEAVE statement:

label WHILE condition
   ......
   LEAVE label; 
   ......
END WHILE label

A good exercise of using loop statements and break statements is to calculate prime numbers. Here is my example:

-- PrimeNumbers.sql
-- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
--
DROP DATABASE IF EXISTS HyTest;
CREATE DATABASE HyTest;
USE HyTest;
--
DROP PROCEDURE IF EXISTS SetPrimeNunmbers;
DELIMITER '/';
CREATE PROCEDURE InitTable(IN N INTEGER)
BEGIN
   DECLARE I, P, D INTEGER;
   DECLARE PrimeFound INTEGER;
   SET I = 0;
   SET P = 2; 
   WHILE I < N DO
      SET PrimeFound = 0;
      NextPrime: LOOP 
         SET P = P + 1;          
         SET D = P DIV 2;
         WHILE D > 1 DO
            IF P MOD D = 0 THEN
               ITERATE NextPrime;
            END IF;
            SET D = D - 1;
         END WHILE;
         LEAVE NextPrime;
      END LOOP NextPrime;
      INSERT INTO PrimeNumber VALUES (I, P);
      SET I = I + 1;
   END WHILE;
END/
DELIMITER ';'/
--
DROP TABLE IF EXISTS MyTable;
CREATE TABLE PrimeNumber (ID INTEGER, Prime INTEGER);
CALL InitTable(20);
SELECT 'Table detail :' AS '---';
SELECT * FROM PrimeNumber WHERE ID < 20;

Output:

---
Table detail :
ID      Prime
0       3
1       5
2       7
3       11
4       13
5       17
6       19
7       23
8       29
9       31
10      37
11      41
12      43
13      47
14      53
15      59
16      61
17      67
18      71
19      73

Last update: 2015.

Table of Contents

 About This Book

 Introduction of SQL

 MySQL Introduction and Installation

 Introduction of MySQL Programs

 Perl Programs and MySQL Servers

 PHP Programs and MySQL Servers

 Java Programs and MySQL Servers

 Datatypes and Data Literals

 Operations and Expressions

 Character Strings and Bit Strings

 Commonly Used Functions

 Table Column Types for Different Types of Values

 Using DDL to Create Tables and Indexes

 Using DML to Insert, Update and Delete Records

 Using SELECT to Query Database

 Transaction Management and Isolation Levels

 Locks Used in MySQL

 Defining and Calling Stored Procedures

Variables, Loops and Cursors Used in Stored Procedures

 Local Variables in Stored Procedures

 Execution Flow Control Statements

ITERATE and LEAVE - Statements to Break Loops

 DECLARE ... CURSOR FOR Select Statements

 Outdated Tutorials

 References

 PDF Printing Version