Stored Procedures and Functions

Table of Contents

140. Stored Procedure Syntax
Maintaining Stored Procedures
CREATE PROCEDURE and CREATE FUNCTION
ALTER PROCEDURE and ALTER FUNCTION
DROP PROCEDURE and DROP FUNCTION
SHOW CREATE PROCEDURE and SHOW CREATE FUNCTION
SHOW PROCEDURE STATUS and SHOW FUNCTION STATUS
CALL
BEGIN ... END Compound Statement
DECLARE Statement
Variables in Stored Procedures
DECLARE Local Variables
Variable SET Statement
SELECT ... INTO Statement
Conditions and Handlers
DECLARE Conditions
DECLARE Handlers
Cursors
Declaring Cursors
Cursor OPEN Statement
Cursor FETCH Statement
Cursor CLOSE Statement
Flow Control Constructs
IF Statement
CASE Statement
LOOP Statement
LEAVE Statement
ITERATE Statement
REPEAT Statement
WHILE Statement

Stored procedures and functions are a new feature in MySQL version 5.0. A stored procedure is a set of SQL commands that can be stored in the server. Once this has been done, clients don't need to keep re-issuing the individual commands but can refer to the stored procedure instead.

Stored procedures can provide improved performance as less information needs to be sent between the server and the client. The trade-off is that this does increase the load on the database server system, as more of the work is done on the server side and less on the client (application) side. And often, there are multiple client machines (such as web servers) but only one or a few database servers.

Stored procedures also allow you to have libraries of functions in the database server. However, modern application languages already allow such design internally with for instance classes, and using these client application language features is beneficial for the programmer even outside the scope of database use.

Situations where using stored procedures makes sense:

MySQL follows the SQL:2003 syntax for stored procedures, which is also used by IBM's DB2. Compatibility support for other stored procedure languages (PL/SQL, T-SQL) may be added later.

The MySQL implementation of stored procedures is still in progress. All syntax described in this chapter is supported and any limitations and extensions are documented where appropriate.

Stored procedures require the proc table in the mysql database. This table is created during the MySQL 5.0 installation procedure. If you are upgrading to MySQL 5.0 from an earlier version, be sure to update your grant tables to make sure the proc table exists. See Upgrading-grant-tables.