Synchronization using triggers
-
02-11-2019 - |
Question
I have a requirement similar to previous discussions at:
- Writing a simple bank schema: How should I keep my balances in sync with their transaction history?
- Trigger in combination with transaction
I have two tables, [Account].[Balance]
and [Transaction].[Amount]
:
CREATE TABLE Account (
AccountID INT
, Balance MONEY
);
CREATE TABLE Transaction (
TransactionID INT
, AccountID INT
, Amount MONEY
);
When there is an insert, update or delete against the [Transaction]
table, the [Account].[Balance]
should be updated based on the [Amount]
.
Currently I have a trigger to do this job:
ALTER TRIGGER [dbo].[TransactionChanged]
ON [dbo].[Transaction]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
IF EXISTS (select 1 from [Deleted]) OR EXISTS (select 1 from [Inserted])
UPDATE [dbo].[Account]
SET
[Account].[Balance] = [Account].[Balance] +
(
Select ISNULL(Sum([Inserted].[Amount]),0)
From [Inserted]
Where [Account].[AccountID] = [Inserted].[AccountID]
)
-
(
Select ISNULL(Sum([Deleted].[Amount]),0)
From [Deleted]
Where [Account].[AccountID] = [Deleted].[AccountID]
)
END
Although this seems to be working, I have questions:
- Does the trigger follow the relational database's ACID principle? Is there any chance an insert might be committed but the trigger fail?
- My
IF
andUPDATE
statements look strange. Is there any better way to update the correct[Account]
row?
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange