Working with Stored Procedures in SQL

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.

Advantages of Stored Procedures

Stored procedures offer several benefits that make them a preferred method for executing SQL tasks:

  • Modularity and Reusability: SQL code can be stored and reused as needed, promoting code modularity.
  • Improved Performance: Since stored procedures are precompiled, their execution is faster than running individual SQL statements.
  • Security: You can grant users permission to execute stored procedures without giving them direct access to the underlying tables.
  • Reduced Network Traffic: Stored procedures run on the server, so instead of sending multiple SQL statements over the network, only the procedure call is sent.
  • Maintainability: If you need to update your SQL logic, you only have to modify the stored procedure, making it easier to maintain the code.

Creating Stored Procedures

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.

Syntax:

				
					CREATE PROCEDURE procedure_name
AS
BEGIN
    -- SQL statements go here
END;

				
			

Example:

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.

Executing Stored Procedures

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.

Syntax:

				
					EXEC procedure_name;

				
			

Example:

				
					EXEC GetAllEmployees;

				
			

Output:

employee_idnamedepartmentsalary
1AliceHR50000
2BobIT60000
3CharlieMarketing55000

Parameters in Stored Procedures

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.

Syntax:

				
					CREATE PROCEDURE procedure_name (parameter_name datatype)
AS
BEGIN
    -- SQL statements
END;

				
			

Example with Parameters:

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_idnamedepartmentsalary
2BobIT60000

IN, OUT, and INOUT Parameters

SQL stored procedures can accept three types of parameters:

  • IN: The default parameter type, which passes values into the procedure. Changes made to the parameter inside the procedure do not affect the original value.
  • OUT: This type returns a value from the procedure. The value of the parameter can be changed inside the procedure, and the result is passed back to the calling program.
  • INOUT: Combines the behavior of both IN and OUT. It can pass a value into the procedure and return a modified value.

Example of IN, OUT, and INOUT Parameters:

				
					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.

Example Execution:

				
					DECLARE @salary DECIMAL;
EXEC AddBonus(2, 5000, @salary);
SELECT @salary AS NewSalary;

				
			

Output:

NewSalary
65000

Conditional Logic and Control Flow in Stored Procedures

Stored procedures support control flow constructs like IF, WHILE, and CASE, allowing you to build complex logic into your procedures.

Example of Conditional Logic:

				
					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 in Stored Procedures

Error handling is crucial in stored procedures to ensure robust execution. SQL offers the TRY...CATCH block for handling errors within stored procedures.

Example of Error Handling:

				
					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.

Modifying and Deleting Stored Procedures

Modifying a Stored Procedure:

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;

				
			

Deleting a Stored Procedure:

To remove a stored procedure from the database, use the DROP PROCEDURE statement.

				
					DROP PROCEDURE GetAllEmployees;

				
			

Stored Procedures vs Functions

Stored procedures and functions are similar but have some key differences:

  • Return Type: Stored procedures can return zero or more values (using OUT parameters), while functions must return a single value or table.
  • Use in Queries: Functions can be used within SQL statements (e.g., in SELECT), whereas stored procedures cannot.
  • Side Effects: Stored procedures can perform operations like inserting, updating, and deleting data. Functions are usually limited to calculations and cannot modify the database.

Example:

				
					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 !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India