Search code examples
sqlsql-serverindexingtriggersindexed-views

Indexed views: How to insert value into other table with index views?


My table:

CREATE TABLE [dbo].[Balance] (
    [Id]             INT             IDENTITY (1, 1) NOT NULL,    
    [Balance]        DECIMAL (18, 2) NOT NULL,
    [Today_Date]     AS              (CONVERT([char](10),getdate(),(126))),
    [Date_end]       DATE            NOT NULL,
    [Remaining_Days] AS              (datediff(day,CONVERT([char](10),getdate(),(126)),[Date_end])),
    [In_Months]      AS              (datediff(day,CONVERT([char](10),getdate(),(126)),[Date_end]))/(30),
    [Amount_Monthly] AS              CAST((case when ((datediff(day,CONVERT([char](10),getdate(),(126)),[Date_end]))/30) = 0 then NULL else [Balance]/((datediff(day,CONVERT([char](10),getdate(),(126)),[Date_end]))/30) end) as DECIMAL(18,2)),
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

How it looks like:

My data

I want it to automatically insert the Amount_Monthly into a new table so it would look like this:

My Months table

E.g. if it says In_Months = 2 it should fill out January and February's Balance_monthly to 7058,82. I want it to calculate it automatically Just like I made it automatically calculate remaining_days depending on the input.

Thank you!


Solution

  • @Mahesh So, @Usedbyalready's answer seemed pretty overkill, I tried making it myself with case inside an update and it works perfectly.

    UPDATE Months
    SET Months.Balance_monthly = 
        CASE 
            WHEN Balance.In_Months > 1 THEN Amount_Monthly          
        END
    FROM Balance
    JOIN Months 
    ON Months.Id <= Balance.In_Months;
    

    I also made a trigger that automatically inserts the values into my Months table:

    CREATE TRIGGER [Balance_monthly]
    ON [dbo].[Balance]
    FOR INSERT, UPDATE
    AS
    BEGIN
        SET NOCOUNT ON
    
        UPDATE Months
        SET Months.Balance_monthly = 
        ((Balance.In_Months + 12 - Months.Id) / 12) * Amount_Monthly          
        FROM Balance
        CROSS JOIN Months;
    
    
    END