Stored Procedure Overview
Stored procedures are precompiled collections of SQL statements stored on the server, allowing for encapsulated logic, parameterized execution, and improved application performance.
A Stored Procedure is a routine invoked with a CALL statement. It may have input parameters, output parameters and parameters that are both input parameters and output parameters.
Creating a Stored Procedure
Here's a skeleton example to see a stored procedure in action:
DELIMITER //
CREATE PROCEDURE Reset_animal_count()
MODIFIES SQL DATA
UPDATE animal_count SET animals = 0;
//
DELIMITER ;First, the delimiter is changed, since the function definition will contain the regular semicolon delimiter. The procedure is named Reset_animal_count. MODIFIES SQL DATA indicates that the procedure will perform a write action of sorts, and modify data. It's for advisory purposes only. Finally, there's the actual SQL statement - an UPDATE.
SELECT * FROM animal_count;
+---------+
| animals |
+---------+
| 101 |
+---------+
CALL Reset_animal_count();
SELECT * FROM animal_count;
+---------+
| animals |
+---------+
| 0 |
+---------+A more complex example, with input parameters, from an actual procedure used by banks:
See CREATE PROCEDURE for full syntax details.
Why use Stored Procedures?
Security is a key reason. Banks commonly use stored procedures so that applications and users don't have direct access to the tables. Stored procedures are also useful in an environment where multiple languages and clients are all used to perform the same operations.
Stored Procedure listings and definitions
To find which stored functions are running on the server, use SHOW PROCEDURE STATUS.
or query the routines table in the INFORMATION_SCHEMA database directly:
To find out what the stored procedure does, use SHOW CREATE PROCEDURE.
Dropping and Updating a Stored Procedure
To drop a stored procedure, use the DROP PROCEDURE statement.
To change the characteristics of a stored procedure, use ALTER PROCEDURE. However, you cannot change the parameters or body of a stored procedure using this statement; to make such changes, you must drop and re-create the procedure using CREATE OR REPLACE PROCEDURE (which retains existing privileges), or DROP PROCEDURE followed CREATE PROCEDURE .
Permissions in Stored Procedures
See the article Stored Routine Privileges.
This page is licensed: CC BY-SA / Gnu FDL
Last updated
Was this helpful?

