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.

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

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




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


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


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.


Increment the counter variable by one.


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.


We proudly announce that we can count to 10!

Part I: Stored Programming Fundamentals

Introduction to MySQL Stored Programs

MySQL Stored Programming Tutorial

Language Fundamentals

Blocks, Conditional Statements, and Iterative Programming

Using SQL in Stored Programming

Error Handling

Part II: Stored Program Construction

Creating and Maintaining Stored Programs

Transaction Management

MySQL Built-in Functions

Stored Functions


Part III: Using MySQL Stored Programs in Applications

Using MySQL Stored Programs in Applications

Using MySQL Stored Programs with PHP

Using MySQL Stored Programs with Java

Using MySQL Stored Programs with Perl

Using MySQL Stored Programs with Python

Using MySQL Stored Programs with .NET

Part IV: Optimizing Stored Programs

Stored Program Security

Tuning Stored Programs and Their SQL

Basic SQL Tuning

Advanced SQL Tuning

Optimizing Stored Program Code

Best Practices in MySQL Stored Program Development

MySQL Stored Procedure Programming
MySQL Stored Procedure Programming
ISBN: 0596100892
EAN: 2147483647
Year: 2004
Pages: 208

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net