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
--
DROP DATABASE IF EXISTS HyTest;
CREATE DATABASE HyTest;
USE HyTest;
--
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.