In MySQL, stored procedures and functions allow developers to encapsulate reusable SQL logic on the database server. One of their core features is the ability to accept parameters, enabling dynamic and flexible execution based on input values. Parameters provide a way to pass data into stored procedures and functions, and also return data back to the caller.
This article provides an in-depth exploration of using parameters with stored procedures and functions in MySQL. We will cover parameter types, syntax, usage patterns, best practices, and provide extensive examples to help you master this crucial feature.
| Feature | Stored Procedure | Function |
|---|---|---|
| Purpose | Perform actions (e.g., DML operations, complex logic) and optionally return multiple result sets. | Return a single value, typically used in expressions and queries. |
| Return Type | No explicit return type; results returned via SELECT or OUT parameters. | Must have a defined return data type. |
| Use in SQL | Called with CALL statement. | Can be used inside queries like SELECT myFunction(args). |
| Parameters | IN, OUT, and INOUT parameters allowed. | Only IN parameters allowed. |
MySQL supports three kinds of parameters in stored procedures:
Functions accept only IN parameters.
CREATE PROCEDURE procedure_name (
[IN|OUT|INOUT] param_name datatype,
...
)
BEGIN
-- procedure body
END;
IN parameters are used to pass values into the procedure. Inside the procedure, these parameters act like constants and cannot be modified.
DELIMITER //
CREATE PROCEDURE GetEmployeesByDept(IN dept VARCHAR(50))
BEGIN
SELECT employee_id, name, department
FROM employees
WHERE department = dept;
END //
DELIMITER ;
Execution:
CALL GetEmployeesByDept('Finance');
OUT parameters are used to return values from the procedure to the caller. The procedure assigns a value to the OUT parameter which can then be retrieved by the caller.
DELIMITER //
CREATE PROCEDURE GetEmployeeCountByDept(
IN dept VARCHAR(50),
OUT emp_count INT
)
BEGIN
SELECT COUNT(*) INTO emp_count
FROM employees
WHERE department = dept;
END //
DELIMITER ;
Execution and retrieval:
CALL GetEmployeeCountByDept('HR', @count);
SELECT @count;
INOUT parameters allow passing a value in and receiving a modified value back. They behave as both input and output parameters.
DELIMITER //
CREATE PROCEDURE IncreaseSalary(INOUT current_salary DECIMAL(10,2))
BEGIN
SET current_salary = current_salary * 1.1; -- Increase by 10%
END //
DELIMITER ;
Execution:
SET @salary = 50000;
CALL IncreaseSalary(@salary);
SELECT @salary; -- 55000
MySQL functions are simpler than procedures in terms of parameter usage, only allowing IN parameters. This is because functions are meant to be used inside expressions and must be deterministic in their output given the same inputs.
CREATE FUNCTION function_name (param_name datatype, ...)
RETURNS datatype
BEGIN
-- function body
RETURN value;
END;
This function calculates the yearly salary based on a monthly salary input.
DELIMITER //
CREATE FUNCTION YearlySalary(monthly_salary DECIMAL(10,2))
RETURNS DECIMAL(10,2)
BEGIN
RETURN monthly_salary * 12;
END //
DELIMITER ;
Usage:
SELECT YearlySalary(4000); -- Returns 48000
You can assign parameter values to local variables for further manipulation.
DECLARE local_var datatype;
SET local_var = param_name;
OUT and INOUT parameters can be assigned new values inside the procedure body using SET or SELECT INTO.
DELIMITER //
CREATE PROCEDURE CalculateBonus(
IN emp_id INT,
OUT bonus DECIMAL(10,2)
)
BEGIN
DECLARE base_salary DECIMAL(10,2);
SELECT salary INTO base_salary FROM employees WHERE employee_id = emp_id;
SET bonus = base_salary * 0.1;
END //
DELIMITER ;
Simply supply the argument value in the CALL statement:
CALL ProcedureName('value');
Use user-defined variables prefixed with @ when calling the procedure and then select their values afterward:
CALL ProcedureName('input', @out_param);
SELECT @out_param;
CALL UpdateEmployeeStatus(101, 'active', @message);
SELECT @message;
Procedures can validate input parameters and signal errors if invalid values are provided, using SIGNAL to raise exceptions:
DELIMITER //
CREATE PROCEDURE UpdateEmployeeStatus(
IN emp_id INT,
IN new_status VARCHAR(20)
)
BEGIN
IF new_status NOT IN ('active', 'inactive', 'terminated') THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Invalid status value';
END IF;
UPDATE employees SET employment_status = new_status WHERE employee_id = emp_id;
END //
DELIMITER ;
You can use parameters to build dynamic SQL statements inside stored procedures with PREPARE and EXECUTE statements.
DELIMITER //
CREATE PROCEDURE SearchEmployeesByColumn(
IN column_name VARCHAR(64),
IN search_value VARCHAR(100)
)
BEGIN
SET @sql = CONCAT('SELECT * FROM employees WHERE ', column_name, ' = ?');
PREPARE stmt FROM @sql;
SET @val = search_value;
EXECUTE stmt USING @val;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
CALL SearchEmployeesByColumn('department', 'Sales');Parameters are fundamental to the power and flexibility of MySQL stored procedures and functions. IN parameters allow data to be passed in, OUT and INOUT parameters enable data to be passed back, and functions rely on IN parameters to compute and return values. Mastery of parameters facilitates modular, reusable, and secure SQL code within your database environment.
Remember to always validate inputs, use clear naming conventions, and handle parameters carefully to avoid bugs and maximize maintainability.
Use the command: CREATE INDEX index_name ON table_name (column_name); to create an index on a MySQL table.
To install MySQL on Windows, download the installer from the official MySQL website, run the setup, and follow the installation wizard to configure the server and set up user accounts.
MySQL is an open-source relational database management system (RDBMS) that uses SQL (Structured Query Language) for managing and manipulating databases. It is widely used in web applications for its speed and reliability.
Use the command: INSERT INTO table_name (column1, column2) VALUES (value1, value2); to add records to a MySQL table.
Use the command: mysql -u username -p database_name < data.sql; to import data from a SQL file into a MySQL database.
DELETE removes records based on a condition and can be rolled back, while TRUNCATE removes all records from a table and cannot be rolled back.
A trigger is a set of SQL statements that automatically execute in response to certain events on a MySQL table, such as INSERT, UPDATE, or DELETE.
The default MySQL port is 3306, and the root password is set during installation. If not set, you may need to configure it manually.
Replication in MySQL allows data from one MySQL server (master) to be copied to one or more servers (slaves), providing data redundancy and load balancing.
A primary key is a unique identifier for a record in a MySQL table, ensuring that no two records have the same key value.
Use the command: SELECT column1, column2 FROM table_name; to fetch data from a MySQL table.
Use the command: CREATE DATABASE database_name; to create a new MySQL database.
Use the command: CREATE PROCEDURE procedure_name() BEGIN SQL_statements; END; to define a stored procedure in MySQL.
Indexing in MySQL improves query performance by allowing the database to find rows more quickly. Common index types include PRIMARY KEY, UNIQUE, and FULLTEXT.
Use the command: UPDATE table_name SET column1 = value1 WHERE condition; to modify existing records in a MySQL table.
CHAR is a fixed-length string data type, while VARCHAR is variable-length. CHAR is faster for fixed-size data, whereas VARCHAR saves space for variable-length data.
MyISAM is a storage engine that offers fast read operations but lacks support for transactions, while InnoDB supports transactions and foreign keys, providing better data integrity.
A stored procedure is a set of SQL statements that can be stored and executed on the MySQL server, allowing for modular programming and code reuse.
Use the command: mysqldump -u username -p database_name > backup.sql; to create a backup of a MySQL database.
Use the command: DELETE FROM table_name WHERE condition; to remove records from a MySQL table.
A foreign key is a column or set of columns in one MySQL table that references the primary key in another, establishing a relationship between the two tables.
Use the command: CREATE TRIGGER trigger_name BEFORE INSERT ON table_name FOR EACH ROW BEGIN SQL_statements; END; to create a trigger in MySQL.
Normalization in MySQL is the process of organizing data to reduce redundancy and improve data integrity by dividing large tables into smaller ones.
JOIN is used to combine rows from two or more MySQL tables based on a related column, allowing for complex queries and data retrieval.
Use the command: mysqldump -u username -p database_name > backup.sql; to export a MySQL database to a SQL file.
Copyrights © 2024 letsupdateskills All rights reserved