Skip to Content
MySQL Stored Procedure Programming
book

MySQL Stored Procedure Programming

by Guy Harrison, Steven Feuerstein
March 2006
Intermediate to advanced
640 pages
17h 8m
English
O'Reilly Media, Inc.
Content preview from MySQL Stored Procedure Programming

Loops

Loops allow stored programs to execute statements repetitively. The MySQL stored program language offers three types of loops :

  • Simple loops using the LOOP and END LOOP clauses

  • Loops that continue while a condition is true, using the WHILE and END WHILE clauses

  • Loops that continue until a condition is true, using the REPEAT and UNTIL clauses

With all three loop types, you terminate execution of the loop with the LEAVE statement.

All three types of loops are described in detail in Chapter 4; we'll only demonstrate the LOOP-LEAVE-END LOOP (simple loop) sequence in this tutorial.

Figure 2-9 shows a very simple loop.

A simple loop inside a stored procedure

Figure 2-9. A simple loop inside a stored procedure

Here is an explanation of the activity in this stored procedure:

Line(s)

Explanation

7

Declare a simple numeric variable called counter with an initial value of 0.

9-14

The simple loop. All statements between LOOP and END LOOP are repeated until a LEAVE clause is executed.

9

The LOOP statement is prefixed by the my_simple_loop: label. The LEAVE statement requires that the loop be labeled so it knows which loop to exit.

10

Increment the counter variable by one.

11-13

Test for the value of counter. If the value of counter is 10, we execute the LEAVE statement to terminate the loop. Otherwise, we continue with the next iteration of the loop.

15

We proudly announce that we can count to 10!

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

MySQL and JSON: A Practical Programming Guide

MySQL and JSON: A Practical Programming Guide

David Stokes
MySQL 8 Cookbook

MySQL 8 Cookbook

Karthik Appigatla
Advanced MySQL 8

Advanced MySQL 8

Eric Vanier, Birju Shah, Tejaswi Malepati

Publisher Resources

ISBN: 0596100892Supplemental ContentErrata Page