Skip to Main Content
MySQL Stored Procedure Programming
book

MySQL Stored Procedure Programming

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

Name

LOOP-04: Use a simple loop to avoid redundant code required by a WHILE or REPEAT UNTIL loop

Synopsis

This guideline is particularly relevant when you are writing cursor loops.

The structure of MySQL cursors, and the necessity of setting an indicator variable to detect the end of the cursor, means that you usually want to execute the cursor loop at least once. You will then continue executing the loop until the indicator variable changes.

This sounds like a perfect opportunity to apply the REPEAT UNTIL loop. So as you start to create the program, you create a structure that looks like this:

    DECLARE dept_csr CURSOR FOR
         SELECT department_name
           FROM departments;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_departments=1;

    OPEN dept_csr;
    REPEAT
        FETCH dept_csr INTO  v_department_name;
    UNTIL (no_more_departments) END REPEAT;

    CLOSE dept_csr;
    SET no_more_departments=0;

Of course, you always want to do something with the data fetched from a cursor, but you need to make sure that you don't try to process data after the last row has been returned. So in order to keep the REPEAT loop, you create an IF structure to enclose your processing:

    DECLARE dept_csr CURSOR FOR
     SELECT department_name
       FROM departments;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET no_more_departments=1;

       OPEN dept_csr;
       REPEAT
            FETCH dept_csr INTO  v_department_name;
                 IF (no_more_departments=0) THEN
                SET v_count= v_count+1;
                 END IF;
       UNTIL (no_more_departments) END REPEAT;

           CLOSE dept_csr;
        SET no_more_departments=0;

The problem with ...

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 Concurrency: Locking and Transactions for MySQL Developers and DBAs

MySQL Concurrency: Locking and Transactions for MySQL Developers and DBAs

Jesper Wisborg Krogh
MySQL 8 Administrator???s Guide

MySQL 8 Administrator???s Guide

Chintan Mehta, Hetal Oza, Subhash Shah, Ravi Shah
MySQL Cookbook, 4th Edition

MySQL Cookbook, 4th Edition

Sveta Smirnova, Alkin Tezuysal
Learning MySQL, 2nd Edition

Learning MySQL, 2nd Edition

Vinicius M. Grippa, Sergey Kuzmichev

Publisher Resources

ISBN: 0596100892Supplemental ContentErrata Page