Creating Stored Procedures

Stored procedures are precompiled SQL statements that can be executed repeatedly. They offer benefits such as improved performance, enhanced security, and modularity.

Basic Syntax for Creating a Stored Procedure

The fundamental syntax for creating a stored procedure in SQL Server uses the CREATE PROCEDURE statement.

CREATE PROCEDURE procedure_name
                [ (@parameter1 datatype [= default_value] [OUTPUT],
                  @parameter2 datatype [= default_value] [OUTPUT],
                  ...) ]
            AS
            BEGIN
                -- SQL statements go here
                SELECT column_name FROM table_name WHERE condition;
            END;
            

Explanation:

Example: Creating a Simple Procedure

This example demonstrates creating a procedure that retrieves all employees from an Employees table.

CREATE PROCEDURE Get_All_Employees
            AS
            BEGIN
                -- Select all columns from the Employees table
                SELECT *
                FROM Employees;
            END;
            

Example: Creating a Procedure with Parameters

This procedure retrieves employees based on their department ID.

CREATE PROCEDURE Get_Employees_By_Department
                @DepartmentID INT
            AS
            BEGIN
                -- Select employees matching the provided DepartmentID
                SELECT *
                FROM Employees
                WHERE DepartmentID = @DepartmentID;
            END;
            

Example: Creating a Procedure with an OUTPUT Parameter

This procedure counts the number of employees in a given department and returns the count via an OUTPUT parameter.

CREATE PROCEDURE Count_Employees_By_Department
                @DepartmentID INT,
                @EmployeeCount INT OUTPUT
            AS
            BEGIN
                -- Count employees and assign to the OUTPUT parameter
                SELECT @EmployeeCount = COUNT(*)
                FROM Employees
                WHERE DepartmentID = @DepartmentID;
            END;
            

Tip

Using OUTPUT parameters allows your stored procedures to return single values or status information back to the caller.

Important Considerations

Note

The syntax and features might vary slightly between different SQL database systems (e.g., SQL Server, PostgreSQL, MySQL). This documentation focuses on SQL Server syntax.