Stored Procedure

Stored procedures are precompiled sets of one or more SQL statements that can be executed together. They are stored in the database and can be accessed by applications, other stored procedures, or scripts. These procedures encapsulate intricate SQL logic, making maintenance and reusability easier.

Characteristics

  1. Precompiled: Stored procedures are compiled and saved in the database, potentially improving performance.
  2. Reusable: Once created, they can be utilized multiple times by various applications.
  3. Modular: They enable you to consolidate complex logic into a single callable unit.
  4. Secure: Data access can be finely controlled by granting permissions on stored procedures rather than tables.
  5. Maintainable: Modifications to the procedure logic only need to be done in one location.

Advantages of Stored Procedures

  1. Performance
  2. Security
  3. Maintainability and Reusability
  4. Modularity
  5. Transaction Management

Flow of procedure

Flow of procedure

Description of the above flow

Example of procedure

Step 1. The tables used in this procedure are,

Tables

CREATE TABLE Sales (
    SaleID INT PRIMARY KEY,
    AgentID INT,
    SaleAmount DECIMAL(10, 2),
    SaleDate DATETIME
);

CREATE TABLE Inventory (
    ProductID INT PRIMARY KEY,
    ProductName NVARCHAR(100),
    Quantity INT
);

CREATE TABLE Commissions (
    CommissionID INT IDENTITY PRIMARY KEY,
    AgentID INT,
    SaleID INT,
    CommissionAmount DECIMAL(10, 2),
    CommissionDate DATETIME
);

INSERT INTO Inventory (ProductID, ProductName, Quantity)
VALUES 
    (1, 'Drone Model A', 100),
    (2, 'Drone Model B', 50);

Step 2. The created procedure with this table is,

Created procedure

CREATE PROCEDURE ProcessSale
    @SaleID INT,
    @AgentID INT,
    @SaleAmount DECIMAL(10, 2)
AS
BEGIN
    BEGIN TRY
        BEGIN TRANSACTION

        -- Insert a new sales transaction
        INSERT INTO Sales (SaleID, AgentID, SaleAmount, SaleDate)
        VALUES (@SaleID, @AgentID, @SaleAmount, GETDATE());

        -- Update inventory (example logic)
        UPDATE Inventory
        SET Quantity = Quantity - 1
        WHERE ProductID = @SaleID;

        -- Calculate the commission
        DECLARE @Commission DECIMAL(10, 2);
        SET @Commission = dbo.CalculateCommission(@SaleAmount);

        -- Insert commission record
        INSERT INTO Commissions (AgentID, SaleID, CommissionAmount, CommissionDate)
        VALUES (@AgentID, @SaleID, @Commission, GETDATE());

        COMMIT;

        -- Return the result
        SELECT @SaleID AS SaleID, @Commission AS Commission;
    END TRY
    BEGIN CATCH
        ROLLBACK;
        -- Handle the error
        SELECT ERROR_MESSAGE() AS ErrorMessage;
    END CATCH
END;

Upon completion of the stored procedure, the following events are expected to take place.

Function in SQL Server

Functions in SQL Server are essential database objects that contain a series of SQL statements and provide either a single value or a table as output. They are utilized for various purposes, such as performing calculations, data manipulation, and generating specific results based on the input parameters given.

Benefits of Functions

Flow of Function

Flow of Function

Description of the above flow

Types of Functions in SQL Server
 

1. Scalar Functions

Example

CREATE FUNCTION dbo.CalculateDiscount
    (@TotalAmount DECIMAL(10, 2))
RETURNS DECIMAL(10, 2)
AS
BEGIN
    DECLARE @DiscountRate DECIMAL(10, 2) = 0.1; -- 10% discount
    RETURN @TotalAmount * @DiscountRate;
END;

-- Usage:
SELECT dbo.CalculateDiscount(1000.00) AS Discount;

2. Table-Valued Functions (TVFs)

Example

CREATE FUNCTION dbo.GetSalesByAgent
    (@AgentID INT)
RETURNS TABLE
AS
RETURN
(
    SELECT SaleID, SaleAmount, SaleDate
    FROM Sales
    WHERE AgentID = @AgentID
);

-- Usage:
SELECT * FROM dbo.GetSalesByAgent(101);

3. Multi-Statement Table-Valued Functions (mTVFs)

Multi-Statement Table-Valued Functions (mTVFs) in SQL Server are custom functions that produce a table data type and can consist of various statements, including intricate logic and procedural code. In contrast to Inline Table-Valued Functions (iTVFs), which are made up of a single SELECT statement, mTVFs offer greater flexibility and sophistication in their design.

Key Characteristics and Applications of mTVFs

Advantages

Example

CREATE FUNCTION dbo.GetSalesSummaryByAgent
    (@AgentID INT)
RETURNS @SalesSummary TABLE
(
    SaleID INT,
    TotalAmount DECIMAL(10, 2),
    SaleCount INT
)
AS
BEGIN
    INSERT INTO @SalesSummary (SaleID, TotalAmount, SaleCount)
    SELECT SaleID, SUM(SaleAmount), COUNT(*)
    FROM Sales
    WHERE AgentID = @AgentID
    GROUP BY SaleID;

    RETURN;
END;

-- Usage:
SELECT * FROM dbo.GetSalesSummaryByAgent(101);

Usage

Use cases of Procedure

  1. Complex Business Logic: If you have to execute intricate business processes that involve multiple steps, transactions, and conditional logic, stored procedures are the way to go.
  2. Data Modification: If you need to carry out INSERT, UPDATE, or DELETE operations, procedures can handle these operations directly.
  3. Performance: When performance is a primary concern, stored procedures can be optimized and cached by SQL Server, often resulting in faster execution.
  4. Output Parameters: If you need to return multiple values or result sets, stored procedures can return multiple output parameters and result sets.
  5. Security: If you need to control access to data, procedures can encapsulate the logic and limit direct access to tables.

Use cases of function

  1. Scalar Calculations: When you need to perform calculations and return a single value, scalar functions are suitable.
  2. Reusable Logic: When you need to encapsulate reusable logic that returns a single value or a table, functions are appropriate.
  3. Data Transformation: When you need to transform data within a SELECT statement, functions can be used for this purpose.
  4. No Side Effects: When you need to ensure there are no side effects, such as data modifications, functions are the right choice.

When to Use Which?