MySQL Stored Procedures
A stored procedure in MySQL is a reusable set of SQL statements stored in the database. It allows you to encapsulate logic, reduce redundancy, and improve performance by minimizing client-server communication.
Benefits of Stored Procedures
- Reusability: Code can be reused across multiple applications.
- Performance: Reduces network traffic by processing on the server.
- Security: Users can execute stored procedures without direct table access.
- Maintainability: Centralizes business logic for easier updates.
Basic Syntax
Parameters
- IN: The parameter is input-only (default).
- OUT: The parameter is output-only.
- INOUT: The parameter can both accept input and return output.
Examples
1. Simple Stored Procedure
A procedure to display all rows from a table:
Call the procedure:
2. Stored Procedure with Input Parameter
A procedure to find an employee by ID:
Call the procedure:
3. Stored Procedure with Output Parameter
A procedure to get the total number of employees:
Call the procedure:
4. Stored Procedure with INOUT Parameter
A procedure that increments a number:
Call the procedure:
Using Control Flow in Procedures
IF Statement
LOOP Statement
Modifying a Stored Procedure
MySQL does not support direct modification of stored procedures. To modify one, you must:
- Drop the existing procedure.
- Create it again with the desired changes.
Dropping a Stored Procedure
Viewing Stored Procedures
List all stored procedures:
View the code for a procedure:
Best Practices
- Error Handling: Use the
DECLARE
andHANDLER
statements to manage errors gracefully. - Avoid Overuse: Use stored procedures judiciously for tasks requiring server-side logic.
- Use Parameters Wisely: Clearly define input, output, and in-out parameters.
- Optimize Queries: Ensure SQL statements inside procedures are optimized for performance.
Let me know if you need help with advanced examples or troubleshooting!