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

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 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