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?
CREATE PROCEDUREusing_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 PROCEDUREusing_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 ...
Get MySQL Stored Procedure Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.