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

STYL-03: Self-document using block and loop labels

Synopsis

While block and loop labels are often necessary to allow for variable scoping or as targets for LEAVE or ITERATE statements, they can also be a big help in improving the readability of code.

Use a label directly in front of loops and nested blocks:

  • To name that portion of code and thereby self-document what it's doing

  • So that you can repeat that name with the END statement of that block or loop

  • To provide a target for a LEAVE or ITERATE statement

This recommendation is especially important when you have multiple nestings of loops (and possibly inconsistent indentation), as in the following:

    WHILE condition DO
       some code
       WHILE condition DO
          some code
       END WHILE;
       some code
    END WHILE;

Example

In this example we use labels for a block and two nested loops, and then apply them in the appropriate END statements. We can now easily see which loop and block are ending, no matter how badly the code is indented!

    CREATE PROCEDURE display_book_usage(  )
      READS SQL DATA
    BEGIN
       DECLARE v_month INT;
       DECLARE v_x  INT;
       DECLARE yearly_analysis_csr CURSOR FOR SELECT ...;
       DECLARE monthly_analysis_csr CURSOR FOR SELECT ...;

       OPEN yearly_analysis_csr;
       yearly_analysis:
       LOOP
         FETCH yearly_analysis_csr INTO v_month;
         OPEN monthly_analysis_csr;
         monthly_analysis:
         LOOP
           FETCH monthly_analysis_csr INTO v_x;
    ... Lots of monthly analysis code ...
    END LOOP monthly_analysis;
    ...Lots of yearly analysis code
    END LOOP yearly_analysis;

Benefits

If you use labels, it's much ...

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