MySQL CREATE PROCEDURE Statement
In MySQL, a stored procedure is a collection of SQL statements stored on the server and executed as a single unit. The CREATE PROCEDURE
statement is used to define a stored procedure.
Stored procedures improve reusability, consistency, and performance by encapsulating logic that can be reused across multiple queries or applications.
Syntax
Key Components:
procedure_name
: Name of the procedure (unique within a database).parameters
: Input/output parameters (optional).- Each parameter must specify a mode (
IN
,OUT
,INOUT
) and a data type. - Example:
IN param1 INT
.
- Each parameter must specify a mode (
characteristics
: Optional attributes such asDETERMINISTIC
orSQL SECURITY
.BEGIN ... END
: Block containing the SQL statements.
Parameter Modes
IN
:- Passes a value into the procedure.
- Default mode.
OUT
:- Used to return a value from the procedure.
INOUT
:- Passes a value in and returns a value after modification.
Examples
1. Basic Stored Procedure
A procedure without parameters.
Call the procedure:
2. Stored Procedure with IN
Parameter
A procedure that accepts an employee ID and retrieves their details.
Call the procedure:
3. Stored Procedure with OUT
Parameter
A procedure that calculates and returns the total salary.
Call the procedure:
4. Stored Procedure with INOUT
Parameter
A procedure that updates a value and returns the modified result.
Call the procedure:
5. Stored Procedure with Multiple Parameters
A procedure that calculates a discounted price based on an input price and discount rate.
Call the procedure:
Result:
DiscountedPrice |
---|
90.00 |
Managing Stored Procedures
1. Viewing Stored Procedures
To list all stored procedures in a database:
To view the procedure definition:
2. Dropping a Stored Procedure
To delete a procedure:
Characteristics
Optional attributes for procedures:
DETERMINISTIC
/NOT DETERMINISTIC
:- Specifies whether the procedure always produces the same result for the same input.
CONTAINS SQL
/NO SQL
/READS SQL DATA
/MODIFIES SQL DATA
**:- Defines the type of SQL statements the procedure contains.
SQL SECURITY
:- Determines the execution context:
DEFINER
: Executes with the privileges of the procedure's creator.INVOKER
: Executes with the privileges of the user invoking the procedure.
- Determines the execution context:
Advantages of Stored Procedures
- Performance:
- Reduce network overhead by executing multiple SQL statements on the server.
- Reusability:
- Encapsulate logic for use in multiple applications.
- Security:
- Restrict direct access to tables and encapsulate complex logic.
- Maintainability:
- Centralized logic makes updates easier.
Common Use Cases
- Automating business logic.
- Implementing complex calculations.
- Managing data transformations.
- Triggering backend processes.
Let me know if you'd like help with specific examples or further explanations!