Stored procedures are one of the most powerful features of SQL. They allow you to store a set of SQL statements that can be executed later, offering numerous advantages such as modularization, reusability, security, and performance optimization. In this chapter, we'll cover everything you need to know about working with stored procedures in SQL, from the basics to advanced concepts, ensuring you have all the necessary knowledge to effectively utilize them in real-world applications.
A stored procedure is a precompiled collection of one or more SQL statements that are stored under a name and processed as a unit. You can think of it as a function or method in programming languages that encapsulates a block of code to perform a specific task. Once created, stored procedures can be executed by simply calling them by name, and they often accept parameters to process dynamic data.
Stored procedures are widely used for repetitive tasks such as inserting, updating, or deleting records, performing calculations, or generating reports.
Stored procedures offer several benefits that make them a preferred method for executing SQL tasks:
To create a stored procedure, you use the CREATE PROCEDURE
statement, followed by the procedure name, parameters (if any), and the block of SQL code to be executed.
CREATE PROCEDURE procedure_name
AS
BEGIN
-- SQL statements go here
END;
Let’s create a simple stored procedure that retrieves all employees from the employees
table:
CREATE PROCEDURE GetAllEmployees
AS
BEGIN
SELECT * FROM employees;
END;
This stored procedure retrieves all rows from the employees
table. Once created, you can call the procedure to execute it.
To execute a stored procedure, you use the EXEC
or CALL
command followed by the procedure name. If the procedure accepts parameters, you pass them in during execution.
EXEC procedure_name;
EXEC GetAllEmployees;
employee_id | name | department | salary |
---|---|---|---|
1 | Alice | HR | 50000 |
2 | Bob | IT | 60000 |
3 | Charlie | Marketing | 55000 |
Stored procedures can accept parameters to make them more dynamic and flexible. Parameters allow you to pass values to the stored procedure, enabling it to perform tasks on different sets of data without changing the code.
CREATE PROCEDURE procedure_name (parameter_name datatype)
AS
BEGIN
-- SQL statements
END;
Let’s create a procedure that retrieves employees based on their department:
CREATE PROCEDURE GetEmployeesByDepartment
@DepartmentName NVARCHAR(50)
AS
BEGIN
SELECT * FROM employees
WHERE department = @DepartmentName;
END;
You can execute this procedure by passing a department name as an argument:
EXEC GetEmployeesByDepartment 'IT';
Output:
employee_id | name | department | salary |
---|---|---|---|
2 | Bob | IT | 60000 |
SQL stored procedures can accept three types of parameters:
IN
and OUT
. It can pass a value into the procedure and return a modified value.
CREATE PROCEDURE AddBonus (
IN emp_id INT,
IN bonus_amount DECIMAL,
OUT new_salary DECIMAL
)
BEGIN
UPDATE employees
SET salary = salary + bonus_amount
WHERE employee_id = emp_id;
SELECT salary INTO new_salary
FROM employees
WHERE employee_id = emp_id;
END;
In this procedure, you pass an employee_id
and a bonus_amount
, and the procedure updates the employee’s salary and returns the new salary via the OUT
parameter.
DECLARE @salary DECIMAL;
EXEC AddBonus(2, 5000, @salary);
SELECT @salary AS NewSalary;
NewSalary |
---|
65000 |
Stored procedures support control flow constructs like IF
, WHILE
, and CASE
, allowing you to build complex logic into your procedures.
CREATE PROCEDURE UpdateSalary
@EmployeeID INT,
@NewSalary DECIMAL
AS
BEGIN
IF @NewSalary < 40000
BEGIN
PRINT 'Salary too low. Cannot update.';
END
ELSE
BEGIN
UPDATE employees
SET salary = @NewSalary
WHERE employee_id = @EmployeeID;
END
END;
This procedure updates the employee’s salary only if the new salary is above a certain threshold. Otherwise, it prints a message.
Error handling is crucial in stored procedures to ensure robust execution. SQL offers the TRY...CATCH
block for handling errors within stored procedures.
CREATE PROCEDURE SafeDivision
@Dividend DECIMAL,
@Divisor DECIMAL,
@Result DECIMAL OUT
AS
BEGIN
BEGIN TRY
SET @Result = @Dividend / @Divisor;
END TRY
BEGIN CATCH
PRINT 'Error: Division by zero is not allowed.';
SET @Result = NULL;
END CATCH
END;
This procedure safely handles division by zero errors and returns a NULL
result in such cases.
If you need to modify an existing stored procedure, use the ALTER PROCEDURE
statement.
ALTER PROCEDURE GetAllEmployees
AS
BEGIN
SELECT employee_id, name FROM employees;
END;
To remove a stored procedure from the database, use the DROP PROCEDURE
statement.
DROP PROCEDURE GetAllEmployees;
Stored procedures and functions are similar but have some key differences:
SELECT
), whereas stored procedures cannot.
CREATE FUNCTION GetEmployeeSalary (@EmployeeID INT)
RETURNS DECIMAL
AS
BEGIN
RETURN (SELECT salary FROM employees WHERE employee_id = @EmployeeID);
END;
This function returns the salary of an employee, which can be used directly in SQL queries:
SELECT GetEmployeeSalary(1);
Stored procedures are a powerful feature in SQL that allows you to group SQL statements into a single execution unit. They provide performance benefits, enhance security, and improve code maintainability. By using parameters, conditional logic, error handling, and advanced features like IN, OUT, and INOUT parameters, stored procedures become highly flexible and dynamic tools for database operations. Happy coding !❤️