O'Reilly logo

MySQL Stored Procedure Programming by Steven Feuerstein, Guy Harrison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Cursors

When you need to retrieve only a single row from a SELECT statement, using the INTO clause is far easier than declaring, opening, fetching from, and closing a cursor. But does the INTO clause generate some additional work for MySQL or could the INTO clause be more efficient than a cursor? In other words, which of the two stored programs shown in Example 22-20 is more efficient?

Example 22-20. Two equivalent stored programs, one using INTO and the other using a cursor
CREATE PROCEDURE using_into
       ( p_customer_id INT,OUT p_customer_name VARCHAR(30))
    READS SQL DATA
BEGIN
        SELECT customer_name
          INTO p_customer_name
          FROM customers
         WHERE customer_id=p_customer_id;
END;

CREATE PROCEDURE using_cursor
    (p_customer_id INT,OUT  p_customer_name VARCHAR(30))
    READS SQL DATA
BEGIN

    DECLARE cust_csr CURSOR FOR
         SELECT customer_name
           FROM customers
          WHERE customer_id=p_customer_id;

        OPEN cust_csr;
        FETCH cust_csr INTO p_customer_name;
        CLOSE cust_csr;

END;

Certainly, it is simpler to code an INTO statement than to code DECLARE, OPEN, FETCH, and CLOSE statements, and we will probably only bother to do this—when we know that the SQL returns only one row—if there is a specific performance advantage. As it turns out, there is actually a slight performance penalty for using an explicit cursor. Figure 22-10 shows the relative performance of each of the stored programs in Example 22-20—over 11,000 executions, the INTO-based stored program was approximately 15% faster than the stored program that used an explicit ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required