Last modified: November 30, 2024

This article is written in: 🇺🇸

Stored Procedures and Functions in SQL

In the realm of relational databases, stored procedures and functions are powerful tools that allow developers to encapsulate reusable pieces of SQL code. They enhance performance, promote code reusability, and encapsulate business logic within the database itself. By understanding how to create and use stored procedures and functions, you can write more efficient and maintainable database applications.

Stored Procedures

A stored procedure is a precompiled collection of SQL statements and optional control-of-flow statements, stored under a name and processed as a unit. They can accept input parameters, return output parameters, and even return a result set of records. Stored procedures are primarily used for performing repetitive tasks and complex operations that involve multiple SQL statements.

Advantages of Stored Procedures

Creating a Stored Procedure

To create a stored procedure, you use the CREATE PROCEDURE statement. The exact syntax may vary slightly depending on the database system, but the general structure is as follows:

CREATE PROCEDURE procedure_name
    @param1 data_type,
    @param2 data_type OUTPUT,
    ...
AS
BEGIN
    -- SQL statements
    -- You can include control-of-flow statements like IF, WHILE, etc.
END;

Example:

Suppose we have a Customers table, and we want to create a stored procedure to insert a new customer.

CREATE PROCEDURE AddCustomer
    @FirstName VARCHAR(50),
    @LastName VARCHAR(50),
    @Email VARCHAR(100),
    @CustomerID INT OUTPUT
AS
BEGIN
    INSERT INTO Customers (FirstName, LastName, Email)
    VALUES (@FirstName, @LastName, @Email);

    SET @CustomerID = SCOPE_IDENTITY();
END;

Calling a Stored Procedure

To execute a stored procedure, you use the EXEC or EXECUTE statement (in some systems, you can also use CALL).

Example:

DECLARE @NewCustomerID INT;

EXEC AddCustomer
    @FirstName = 'John',
    @LastName = 'Doe',
    @Email = 'john.doe@example.com',
    @CustomerID = @NewCustomerID OUTPUT;

SELECT @NewCustomerID AS 'New Customer ID';

Modifying a Stored Procedure

If you need to change the logic inside a stored procedure, you can use the ALTER PROCEDURE statement.

Example:

ALTER PROCEDURE AddCustomer
    @FirstName VARCHAR(50),
    @LastName VARCHAR(50),
    @Email VARCHAR(100),
    @Phone VARCHAR(20),          -- Added new parameter
    @CustomerID INT OUTPUT
AS
BEGIN
    INSERT INTO Customers (FirstName, LastName, Email, Phone)
    VALUES (@FirstName, @LastName, @Email, @Phone);

    SET @CustomerID = SCOPE_IDENTITY();
END;

Deleting a Stored Procedure

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

Example:

DROP PROCEDURE AddCustomer;

Caution: Dropping a stored procedure is irreversible, and any applications relying on it will fail unless the procedure is recreated.

Functions

A function in SQL is a database object that encapsulates a set of SQL statements and returns a single value. Functions can be used in SQL statements wherever expressions are allowed, such as in SELECT, WHERE, or HAVING clauses. They are primarily used for computations and data retrieval.

Types of Functions

Advantages of Functions

Creating a Scalar Function

To create a function, use the CREATE FUNCTION statement.

Example:

Suppose we need a function to calculate the sales tax for a given amount.

CREATE FUNCTION CalculateTax
(
    @Amount DECIMAL(10, 2),
    @TaxRate DECIMAL(4, 2)
)
RETURNS DECIMAL(10, 2)
AS
BEGIN
    DECLARE @TaxAmount DECIMAL(10, 2);
    SET @TaxAmount = @Amount * (@TaxRate / 100);
    RETURN @TaxAmount;
END;

Using the Function in a Query

You can use the function in SQL statements as follows:

SELECT OrderID, Amount, dbo.CalculateTax(Amount, 8.25) AS TaxAmount
FROM Orders;

For each order, we calculate the tax amount using the CalculateTax function with a tax rate of 8.25%.

Creating a Table-Valued Function

Table-valued functions return a table data type.

Example:

Suppose we want a function that returns all orders for a given customer.

CREATE FUNCTION GetCustomerOrders
(
    @CustomerID INT
)
RETURNS TABLE
AS
RETURN
(
    SELECT OrderID, OrderDate, Amount
    FROM Orders
    WHERE CustomerID = @CustomerID
);

Using the Table-Valued Function:

SELECT * FROM dbo.GetCustomerOrders(123);

Modifying a Function

To change a function, use the ALTER FUNCTION statement.

Example:

ALTER FUNCTION CalculateTax
(
    @Amount DECIMAL(10, 2),
    @TaxRate DECIMAL(4, 2),
    @Discount DECIMAL(10, 2) = 0      -- Added optional parameter with default value
)
RETURNS DECIMAL(10, 2)
AS
BEGIN
    DECLARE @TaxAmount DECIMAL(10, 2);
    SET @TaxAmount = (@Amount - @Discount) * (@TaxRate / 100);
    RETURN @TaxAmount;
END;

Deleting a Function

To remove a function, use the DROP FUNCTION statement.

Example:

DROP FUNCTION CalculateTax;

Differences Between Stored Procedures and Functions

Best Practices for Using Stored Procedures and Functions

Table of Contents

    Stored Procedures and Functions in SQL
    1. Stored Procedures
      1. Advantages of Stored Procedures
      2. Creating a Stored Procedure
      3. Calling a Stored Procedure
      4. Modifying a Stored Procedure
      5. Deleting a Stored Procedure
    2. Functions
      1. Types of Functions
      2. Advantages of Functions
      3. Creating a Scalar Function
      4. Using the Function in a Query
      5. Creating a Table-Valued Function
      6. Modifying a Function
      7. Deleting a Function
      8. Differences Between Stored Procedures and Functions
      9. Best Practices for Using Stored Procedures and Functions