Hi,
this trigger will be executed after the INSERT/UPDATE on AccountMaster table. So condition
IF EXISTS (SELECT 1 FROM AccountMaster WHERE AccountCode = @AccountCode )
returns always true. So change this to
IF EXISTS (SELECT 1 FROM Balances WHERE AccountCode = @AccountCode )
So the trigger is...
ALTER TRIGGER tri_InsertBalance ON AccountMaster
FOR INSERT, UPDATE
AS
DECLARE @AccountCode VARCHAR(100)
SELECT @AccountCode = [AccountCode]
FROM Inserted
DECLARE @BalanceAmount NUMERIC(19,4)
SELECT @BalanceAmount = SUM(DebitAmount - CreditAmount)
FROM Inserted
BEGIN
IF EXISTS (SELECT 1 FROM Balances WHERE AccountCode = @AccountCode )
BEGIN
UPDATE Balances SET BalanceAmount = @BalanceAmount
WHERE AccountCode = @AccountCode
END
ELSE
BEGIN
INSERT INTO Balances (AccountCode, BalanceAmount)
SELECT AccountCode, @BalanceAmount FROM Inserted
END
END
I hope this suits your requirement.. Thank you