How can I create a SQLite Trigger to calculate running totals on the "Actual" table? The following SQL code should update the AccountBalances table so that the Balance column counts from 1, 2, 3, ... rowcount. However, the trigger only updates the 2nd row, even when I turned on recursive_triggers. The result below is row 1 = 1, row 2 = 2, and rows after that are null.
CREATE TEMP TABLE "AccountBalances" (
"Id" INTEGER PRIMARY KEY,
"DateId" INT,
"AccountId" INT,
"AccountCurrAmount" REAL,
"Balance" REAL);
INSERT INTO "AccountBalances"
(DateId, AccountId, AccountCurrAmount)
SELECT DateId, AccountId, Sum(AccountCurrAmount)
FROM Actual
GROUP BY DateId, AccountId
ORDER BY AccountId, DateId;
CREATE TRIGGER UpdateAccountBalance AFTER UPDATE ON AccountBalances
BEGIN
UPDATE AccountBalances
SET Balance = 1 + new.Balance
WHERE Id = new.Id + 1;
END;
PRAGMA recursive_triggers = 'on';
UPDATE AccountBalances
SET Balance = 1
WHERE Id = 1
Please check the value of SQLITE_MAX_TRIGGER_DEPTH. Could it be set to 1 instead of default 1000?
Please check your SQLite version. Before 3.6.18, recursive triggers were not supported.
Please note that the following worked for me 100% OK
drop table "AccountBalances"
CREATE TEMP TABLE "AccountBalances" (
"Id" INTEGER PRIMARY KEY,
"Balance" REAL);
INSERT INTO "AccountBalances" values (1,0)
INSERT INTO "AccountBalances" values (2,0);
INSERT INTO "AccountBalances" values (3,0);
INSERT INTO "AccountBalances" values (4,0);
INSERT INTO "AccountBalances" values (5,0);
INSERT INTO "AccountBalances" values (6,0);
CREATE TRIGGER UpdateAccountBalance AFTER UPDATE ON AccountBalances
BEGIN
UPDATE AccountBalances
SET Balance = 1 + new.Balance
WHERE Id = new.Id + 1;
END;
PRAGMA recursive_triggers = 'on';
UPDATE AccountBalances
SET Balance = 1
WHERE Id = 1
select * from "AccountBalances";
Resulted in:
Id Balance
1 1
2 2
3 3
4 4
5 5
6 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With