MySQL Stored Procedure Parameters
In MySQL, stored procedures can accept parameters that allow them to perform dynamic operations based on the input provided. These parameters can be defined in three modes: IN, OUT, and INOUT. Each mode serves a specific purpose, enabling the stored procedure to either receive input, provide output, or both.
Parameter Modes
IN
Parameter:- Passes a value to the stored procedure.
- This is the default parameter type.
- The value is read-only and cannot be modified inside the procedure.
OUT
Parameter:- Used to return a value from the stored procedure.
- The parameter is write-only and cannot hold an initial value.
INOUT
Parameter:- Combines the features of
IN
andOUT
. - The parameter accepts a value, allows modification inside the procedure, and returns the modified value.
- Combines the features of
Syntax
Examples
1. Using IN
Parameters
A procedure that takes input and performs an operation.
Call the procedure:
2. Using OUT
Parameters
A procedure that calculates and returns a value.
Call the procedure:
Result:
BonusAmount |
---|
500.00 |
3. Using INOUT
Parameters
A procedure that modifies an input value and returns it.
Call the procedure:
Result:
UpdatedSalary |
---|
5500.00 |
4. Combining IN
, OUT
, and INOUT
Parameters
A procedure that demonstrates all three parameter modes.
Call the procedure:
Result:
Score | Feedback |
---|---|
85 | Initial Feedback - Evaluation Completed |
Key Points
Parameter Scope:
- Parameters can be used like variables within the procedure body.
Default Values:
- Parameters do not support default values. You must provide them during the procedure call.
Restrictions:
- Parameter names must be unique and cannot match the names of variables, columns, or other identifiers used in the procedure.
Handling NULL Values:
- When working with
OUT
orINOUT
parameters, ensure the values are not NULL unless explicitly intended.
- When working with
Using Variables with Parameters:
- Use user-defined variables (
@var
) to store and retrieve values fromOUT
orINOUT
parameters.
- Use user-defined variables (
Benefits of Using Parameters
- Reusability:
- Procedures with parameters can handle a wide range of inputs, making them more versatile.
- Efficiency:
- Parameters reduce hardcoding, making procedures more adaptable to changing requirements.
- Dynamic Behavior:
- Combine parameters with conditional logic for customized execution paths.
Practical Use Cases
- Fetching data dynamically based on
IN
parameters. - Returning computed results using
OUT
parameters. - Passing and modifying values via
INOUT
parameters for complex operations.
Let me know if you'd like further examples or additional details!