Stored Procedure Basics

This document provides a fundamental understanding of stored procedures in SQL Server. Stored procedures are precompiled collections of one or more Transact-SQL statements that are stored on the database server. They offer significant advantages in terms of performance, security, and maintainability.

What is a Stored Procedure?

A stored procedure is a routine that you can create, save, and reuse. It can accept input parameters, return output parameters, and contain complex business logic. When executed, the procedure runs on the database server, reducing network traffic and improving execution speed compared to sending individual SQL statements from the client.

Key Benefits of Stored Procedures

Anatomy of a Stored Procedure

A typical stored procedure consists of:

Example: A Simple Stored Procedure

Here's a basic example of a stored procedure that retrieves customer information:


CREATE PROCEDURE GetCustomerInfo
    @CustomerID INT
AS
BEGIN
    SELECT
        CustomerID,
        FirstName,
        LastName,
        EmailAddress
    FROM
        Customers
    WHERE
        CustomerID = @CustomerID;
END;
            

Tip

The CREATE PROCEDURE statement is used to define a new stored procedure. The AS keyword separates the procedure definition from its executable statements. The BEGIN and END keywords enclose the batch of Transact-SQL statements.

Executing a Stored Procedure

To execute the stored procedure defined above, you would use the EXECUTE or EXEC command:


EXEC GetCustomerInfo @CustomerID = 10;
            

This statement will execute the GetCustomerInfo procedure, passing the value 10 as the @CustomerID parameter. The procedure will then query the Customers table and return the details for the customer with CustomerID 10.

Next Steps

This section covered the fundamental concepts of stored procedures. For more detailed information, explore the following topics: