In the world of database management, stored procedures are a fundamental tool that allows you to encapsulate complex SQL logic into reusable units. These procedures can perform various operations such as inserting data, updating records, deleting entries, and even returning results. By using stored procedures, developers can enhance security, improve performance, and simplify application code.
A stored procedure is a precompiled collection of SQL statements that are stored in the database server. They can take input parameters, perform operations on the data, and return output values or result sets. Stored procedures are executed within the context of the database server, which means they run faster than equivalent code written in an application language.
Let's dive into some practical examples to understand how to write and execute stored procedures.
Suppose you have a database with a table named employees that contains columns like id, name, and salary. You want to create a stored procedure that inserts a new employee record into this table.
First, ensure you have the employees table created. If not, you can create it using the following SQL statement:
1CREATE TABLE employees (2id INT PRIMARY KEY,3name VARCHAR(100),4salary DECIMAL(10, 2)5);
Now, let's create a stored procedure named insert_employee that takes three input parameters: id, name, and salary.
1DELIMITER //23CREATE PROCEDURE insert_employee(4IN emp_id INT,5IN emp_name VARCHAR(100),6IN emp_salary DECIMAL(10, 2)7)8BEGIN9INSERT INTO employees (id, name, salary) VALUES (emp_id, emp_name, emp_salary);10END //1112DELIMITER ;
To execute the stored procedure, you can use the CALL statement followed by the procedure name and the input parameters.
CALL insert_employee(1, 'John Doe', 50000);
Query OK, 1 row affected (0.02 sec)
Sometimes, you might want to return values from a stored procedure. Let's create a stored procedure that calculates the average salary of all employees and returns it.
1DELIMITER //23CREATE PROCEDURE get_average_salary(4OUT avg_sal DECIMAL(10, 2)5)6BEGIN7SELECT AVG(salary) INTO avg_sal FROM employees;8END //910DELIMITER ;
To execute this stored procedure and retrieve the output parameter, you can use a variable to store the result.
SET @average_salary = 0;CALL get_average_salary(@average_salary);SELECT @average_salary AS average_salary;
+----------------+ | average_salary | +----------------+ | 50000.00 | +----------------+ 1 row in set (0.02 sec)
Stored procedures can also include error handling mechanisms to manage exceptions that might occur during execution.
1DELIMITER //23CREATE PROCEDURE update_salary(4IN emp_id INT,5IN new_salary DECIMAL(10, 2)6)7BEGIN8DECLARE CONTINUE HANDLER FOR SQLEXCEPTION9BEGIN10-- Rollback any changes if an error occurs11ROLLBACK;12SELECT 'Error: Unable to update salary.' AS message;13END;1415START TRANSACTION;16UPDATE employees SET salary = new_salary WHERE id = emp_id;17COMMIT;18END //1920DELIMITER ;
You can execute this stored procedure to update an employee's salary. If there is an error, it will be caught and handled.
CALL update_salary(1, 55000);
+-----------------------------+ | message | +-----------------------------+ | Success: Salary updated. | +-----------------------------+ 1 row in set (0.02 sec)
In the next section, we will explore transactions and how they can be used to ensure data integrity when performing multiple operations within a stored procedure.
By mastering stored procedures, you'll be well-equipped to handle complex database operations efficiently and securely.