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

IF-03: Make sure that a CASE statement is inclusive, or construct a handler to catch any unmatched cases

Synopsis

If none of the CASE statements match as the input condition, CASE will raise MySQL error 1339 (Case not found for CASE statement). You should either construct an error handler to ignore this error, or ensure that the exception never occurs by including an ELSE clause in every CASE statement (the easier solution).

Example

In the following example, the CASE statement will fail if the customer status is not one of 'PLATINUM', 'GOLD', 'SILVER', or 'BRONZE':

    CASE customer_status
        WHEN 'PLATINUM' THEN
             CALL apply_discount(sale_id,20); /* 20% discount */

        WHEN 'GOLD' THEN
             CALL apply_discount(sale_id,15); /* 15% discount */

        WHEN 'SILVER' THEN
             CALL apply_discount(sale_id,10); /* 10% discount */

        WHEN 'BRONZE' THEN
             CALL apply_discount(sale_id,5); /* 5% discount*/
    END CASE;

Here we add an ELSE clause to avoid the error. Since we don't have anything for the ELSE clause to do, we use a dummy SET statement.

    CASE customer_status
        WHEN 'PLATINUM' THEN
              CALL apply_discount(sale_id,20); /* 20% discount */
        WHEN 'GOLD' THEN
              CALL apply_discount(sale_id,15); /* 15% discount */
        WHEN 'SILVER' THEN
              CALL apply_discount(sale_id,10); /* 10% discount */
        WHEN 'BRONZE' THEN
              CALL apply_discount(sale_id,5); /* 5% discount */
        ELSE
               SET dummy=dummy;
    END CASE;

In this alternative solution, we construct a handler to allow the error to be ignored:

 DECLARE not_found INT DEFAULT 0; DECLARE no_matching_case CONDITION ...
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