Stored Procedures

Stored procedures are a set of one or more Transact-SQL statements that are compiled and stored on the database server. They can be executed repeatedly by multiple users or applications. Stored procedures offer several benefits, including improved performance, enhanced security, and modularity of code.

Key Concepts

Creating a Stored Procedure

You can create a stored procedure using the CREATE PROCEDURE statement. Here's a basic example:

Basic Stored Procedure Example


CREATE PROCEDURE usp_GetCustomerOrders
    @CustomerID INT
AS
BEGIN
    SELECT
        OrderID,
        OrderDate,
        TotalAmount
    FROM
        Orders
    WHERE
        CustomerID = @CustomerID;
END;
                

Explanation:

Executing a Stored Procedure

You can execute a stored procedure using the EXECUTE or EXEC statement:

Executing the Stored Procedure


EXEC usp_GetCustomerOrders @CustomerID = 101;
-- or
EXEC usp_GetCustomerOrders 101;
                

Stored Procedure Options

Stored procedures have various options that can control their behavior. Some common options include:

Modifying and Dropping Stored Procedures

You can modify an existing stored procedure using ALTER PROCEDURE and remove it using DROP PROCEDURE.

Modifying and Dropping


-- Modifying a procedure
ALTER PROCEDURE usp_GetCustomerOrders
    @CustomerID INT,
    @OrderDateFrom DATETIME = NULL
AS
BEGIN
    SELECT
        OrderID,
        OrderDate,
        TotalAmount
    FROM
        Orders
    WHERE
        CustomerID = @CustomerID
        AND (@OrderDateFrom IS NULL OR OrderDate >= @OrderDateFrom);
END;

-- Dropping a procedure
DROP PROCEDURE usp_GetCustomerOrders;
                

Further Reading