tags:

views:

60

answers:

1

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
A: 
  1. Please check the value of SQLITE_MAX_TRIGGER_DEPTH. Could it be set to 1 instead of default 1000?

  2. 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
DVK
You're right about my SQLite version. It didn't work because I used the SQLite Manager 0.5.15 plugin for Firefox. It worked when I used the official sqlite3.exe.
Christopher
It appears that I get "Error: too many levels of trigger recursion" when I use it with a table with more than 1000 rows. I will have to implement running totals another way.
Christopher