Format function in sqlserver


SqlServer, SqlServer Useful functions

FORMAT FUNCTION

 

Some times it so happens that we have  many leading zeros after a decimal number .

For example I am getting a result of a query say value of closing stock  as 66000.000000 .

However I need to keep only 2 zeros after the decimal point and want the result as 66000.00 .

Here is a common trick of using the Format function.


Read More...

Enable and Disable Constraints


SqlServer, SqlServer Useful functions
The best way to insert valid data is with constraints. This is also known as data enforcing data or data integrity. We already know that there are various types of constraints in SQL Server. They are:
  1. Primary key constraint
  2. Default key Constraint
  3. Check Constraint
  4. Foreign key Constraint
  5. Unique key Constraint

Sometimes we need to disable constraints to work with...Here is how to do it


Read More...

Resetting Identity Column Value


SqlServer, SqlServer Useful functions

Identity column of a table is a column whose value increases automatically. A user generally cannot insert a value into an identity column. A table can have only one column that is defined with the identity attribute.

Syntax :

IDENTITY [ ( seed , increment ) ]

Default value of identity is IDENTITY (1,1).

Seed : The seed represents the starting value of an ID and the default value of seed is 1.

Increment : It will represent the incremental value of the ID and the default value of increment is 1.


Read More...

efficient ways to insert multiple rows in SQL


SqlServer, SqlServer Useful functions

Inserting multiple rows efficiently can depend on your SQL dialect, the volume of data, and whether you're scripting or working in an application context. Here are some broadly effective methods across different scenarios:

 


Read More...

Getting Cash-flow-statement


SqlServer, SqlServer Useful functions
    1. Pulls the opening balance for "Cash-In-Hand" from a separate table.
    2. Calculates monthly net cash movement (Credits - Debits).
    3. Computes the running cash balance.
    4. Displays the opening balance as a line item under Receipts.

    Let’s walk through how to implement this step by step.


Read More...

GetMonthlyCashFlowSummary


SqlServer, SqlServer Useful functions

Strategy

  1. Get the opening balance from AccountHierarchyNew (as before).
  2. Aggregate monthly Receipts and Payments from VoucherDetails where Receipt_PaymentMode = 'Cash'.
  3. Calculate Net Flow = Receipts - Payments.
  4. Use SUM(...) OVER (ORDER BY Month) to compute the running balance.
  5. Prepend the opening balance as the first row.

 

โœ… 

 

 


Read More...

Monthly breakdown of Receipts and Payments


SqlServer, SqlServer Useful functions
    • Monthly breakdown of Receipts and Payments
    • ๐Ÿ’ฐ Running cash balance per month
    • ๐Ÿงพ Opening balance carried forward from April 1st

    This will give you a ledger-style view of cash flow across months, which is perfect for financial tracking.

     

    โœ… What We'll Build

     

    Month

    Receipts

    Payments

    Net Flow

    Running Balance

    Apr 2025

    15000.00

    8000.00

    7000.00

    48000.00

    May 2025

    12000.00

    5000.00

    7000.00

    55000.00

    ...

    ...

    ...

    ...

    ...

     

    ๐Ÿง  Strategy

    1. Get the opening balance from AccountHierarchyNew (as before).
    2. Aggregate monthly Receipts and Payments from VoucherDetails where Receipt_PaymentMode = 'Cash'.
    3. Calculate Net Flow = Receipts - Payments.
    4. Use SUM(...) OVER (ORDER BY Month) to compute the running balance.
    5. Prepend the opening balance as the first row.

     

    โœ… Final Monthly Cash Flow Procedure

     

    ALTER PROCEDURE [dbo].[GetMonthlyCashFlowSummary] @FromDate DATE = NULL, @ToDate DATE = NULL AS BEGIN -- Normalize date range IF @FromDate IS NULL SET @FromDate = DATEFROMPARTS(YEAR(GETDATE()), 4, 1); IF @ToDate IS NULL SET @ToDate = EOMONTH(GETDATE()); -- Step 1: Get Opening Balance from AccountHierarchyNew DECLARE @OpeningBalance DECIMAL(18,2); SELECT @OpeningBalance = SUM(TransactionNetAmount) FROM AccountHierarchyNew WHERE Category = 'Cash-In-Hand' AND TransactionDate = DATEFROMPARTS(YEAR(@FromDate), 4, 1); -- Step 2: Monthly Receipts and Payments from VoucherDetails ;WITH MonthlyData AS ( SELECT FORMAT(ReceiptDate, 'yyyy-MM') AS Month, SUM(CASE WHEN TransactionType = 'Credit' THEN TransactionNetAmount ELSE 0 END) AS Receipts, SUM(CASE WHEN TransactionType = 'Debit' THEN TransactionNetAmount ELSE 0 END) AS Payments FROM VoucherDetails WHERE Receipt_PaymentMode = 'Cash' AND ReceiptDate >= @FromDate AND ReceiptDate <= @ToDate GROUP BY FORMAT(ReceiptDate, 'yyyy-MM') ), WithNetFlow AS ( SELECT Month, Receipts, Payments, (Receipts - Payments) AS NetFlow FROM MonthlyData ), WithRunningBalance AS ( SELECT Month, Receipts, Payments, NetFlow, SUM(NetFlow) OVER (ORDER BY Month ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) + ISNULL(@OpeningBalance, 0) AS RunningBalance FROM WithNetFlow ) -- Step 3: Final output with opening balance row SELECT 'Opening Balance' AS Month, NULL AS Receipts, NULL AS Payments, NULL AS NetFlow, @OpeningBalance AS RunningBalance UNION ALL SELECT Month, Receipts, Payments, NetFlow, RunningBalance FROM WithRunningBalance ORDER BY CASE WHEN Month = 'Opening Balance' THEN 0 ELSE 1 END, Month; END;

    ๎ท›๎ทœ๎ท™๎ทš

     

     

    ๐Ÿงพ Output Example

     

    Month

    Receipts

    Payments

    NetFlow

    RunningBalance

    Opening Balance

    NULL

    NULL

    NULL

    41000.00

    2025-04

    15000.00

    8000.00

    7000.00

    48000.00

    2025-05

    12000.00

    5000.00

    7000.00

    55000.00

    ...

    ...

    ...

    ...

    ...

     

     


Read More...

Updated Procedure with Bank Balances


SqlServer, SqlServer Useful functions
ALTER PROCEDURE [dbo].[GetCategoryAccountSummary]
    @FromDate DATE = NULL,
    @ToDate DATE = NULL
AS
BEGIN
    -- Normalize date range
    IF @FromDate IS NULL SET @FromDate = DATEFROMPARTS(YEAR(GETDATE()), 4, 1);
    IF @ToDate IS NULL SET @ToDate = EOMONTH(GETDATE());
 
    -- Cash Opening Balance
    DECLARE @OpeningCashBalance DECIMAL(18,2);
    SELECT @OpeningCashBalance = SUM(TransactionNetAmount)
    FROM AccountHierarchyNew
    WHERE Category = 'Cash-In-Hand'
      AND TransactionDate = DATEFROMPARTS(YEAR(@FromDate), 4, 1);
 
    -- Cash Movement
    DECLARE @CashMovement DECIMAL(18,2);
    SELECT @CashMovement = 
        SUM(CASE WHEN TransactionType = 'Credit' THEN TransactionNetAmount ELSE 0 END) -
        SUM(CASE WHEN TransactionType = 'Debit' THEN TransactionNetAmount ELSE 0 END)
    FROM VoucherDetails
    WHERE Receipt_PaymentMode = 'Cash'
      AND ReceiptDate BETWEEN @FromDate AND @ToDate;
 
    DECLARE @CashBalance DECIMAL(18,2) = ISNULL(@OpeningCashBalance, 0) + ISNULL(@CashMovement, 0);
 
    -- Bank Opening Balance
    DECLARE @OpeningBankBalance DECIMAL(18,2);
    SELECT @OpeningBankBalance = SUM(TransactionNetAmount)
    FROM AccountHierarchyNew
    WHERE AccountType IN ('Canara Bank Current A/c', 'ICICI Bank Current A/c')
      AND TransactionDate = DATEFROMPARTS(YEAR(@FromDate), 4, 1);
 
    -- Bank Movement
    DECLARE @BankMovement DECIMAL(18,2);
    SELECT @BankMovement = 
        SUM(CASE WHEN TransactionType = 'Credit' THEN TransactionNetAmount ELSE 0 END) -
        SUM(CASE WHEN TransactionType = 'Debit' THEN TransactionNetAmount ELSE 0 END)
    FROM VoucherDetails
    WHERE AccountType IN ('Canara Bank Current A/c', 'ICICI Bank Current A/c')
      AND ReceiptDate BETWEEN @FromDate AND @ToDate;
 
    DECLARE @BankBalance DECIMAL(18,2) = ISNULL(@OpeningBankBalance, 0) + ISNULL(@BankMovement, 0);
 
    -- Base data
    CREATE TABLE #BaseData (
        Section NVARCHAR(20),
        Category NVARCHAR(100),
        Account NVARCHAR(100),
        Amount DECIMAL(18, 2),
        SortRank INT
    );
 
    -- Actual voucher data
    INSERT INTO #BaseData (Section, Category, Account, Amount, SortRank)
    SELECT  
        CASE 
            WHEN Prefix IN ('R', 'A') THEN 'Receipts'
            WHEN Prefix = 'V' THEN 'Payments'
        END,
        Receipt_PaymentMode,
        AccountType,
        TransactionNetAmount,
        2
    FROM VoucherDetails
    WHERE Prefix IN ('R', 'A', 'V')
      AND ReceiptDate BETWEEN @FromDate AND @ToDate;
 
    -- Synthetic Opening Balances
    INSERT INTO #BaseData VALUES ('Receipts', 'Cash', 'Opening Balance', @CashBalance, 1);
    INSERT INTO #BaseData VALUES ('Receipts', 'Bank', 'Opening Balance', @BankBalance, 1);
 
    -- Synthetic Closing Balances
    INSERT INTO #BaseData VALUES ('Payments', 'Cash', 'Closing Balance', @CashBalance, 3);
    INSERT INTO #BaseData VALUES ('Payments', 'Bank', 'Closing Balance', @BankBalance, 3);
 
    -- CTEs
    WITH ReceiptsCTE AS (
        SELECT 
            ROW_NUMBER() OVER (ORDER BY SortRank, Category, Account) AS RowNum,
            Category AS ReceiptCategory,
            Account AS ReceiptAccount,
            SUM(Amount) AS Receipts
        FROM #BaseData
        WHERE Section = 'Receipts'
        GROUP BY Category, Account, SortRank
    ),
    PaymentsCTE AS (
        SELECT 
            ROW_NUMBER() OVER (ORDER BY SortRank, Category, Account) AS RowNum,
            Category AS PaymentCategory,
            Account AS PaymentAccount,
            SUM(Amount) AS Payments
        FROM #BaseData
        WHERE Section = 'Payments'
        GROUP BY Category, Account, SortRank
    ),
    Combined AS (
        SELECT 
            R.ReceiptCategory,
            R.ReceiptAccount,
            R.Receipts,
            P.PaymentCategory,
            P.PaymentAccount,
            P.Payments
        FROM ReceiptsCTE R
        FULL OUTER JOIN PaymentsCTE P ON R.RowNum = P.RowNum
    )
 
    -- Final output
    SELECT *
    FROM (
        SELECT 
            ReceiptCategory,
            ReceiptAccount,
            Receipts,
            PaymentCategory,
            PaymentAccount,
            Payments,
            0 AS SortOrder
        FROM Combined
 
        UNION ALL
 
        SELECT 
            'TOTAL',
            NULL,
            SUM(Receipts),
            'TOTAL',
            NULL,
            SUM(Payments),
            1
        FROM Combined
    ) AS FinalResult
    ORDER BY SortOrder,
             CASE 
                 WHEN ReceiptCategory = 'Cash' AND ReceiptAccount = 'Opening Balance' THEN 0
                 WHEN ReceiptCategory = 'Bank' AND ReceiptAccount = 'Opening Balance' THEN 1
                 ELSE 2
             END,
             CASE 
                 WHEN PaymentCategory = 'Cash' AND PaymentAccount = 'Closing Balance' THEN 2
                 WHEN PaymentCategory = 'Bank' AND PaymentAccount = 'Closing Balance' THEN 3
                 ELSE 1
             END,
             ReceiptCategory,
             ReceiptAccount;
 
    DROP TABLE #BaseData;
END;

Read More...