使用触发器计算SQLite表中的运行总计

时间:2010-06-05 01:09:58

标签: sql sqlite

如何创建SQLite触发器来计算“实际”表上的运行总计?以下SQL代码应更新AccountBalances表,以便Balance列从1,2,3,... rowcount开始计数。但是,即使我打开recursive_triggers,触发器也只更新第二行。下面的结果是第1行= 1,第2行= 2,之后的行为空。

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

1 个答案:

答案 0 :(得分:0)

  1. 请检查SQLITE_MAX_TRIGGER_DEPTH的值。它可以设置为1而不是默认值1000吗?

  2. 请检查您的SQLite版本。在3.6.18之前,不支持递归触发器。

  3. 请注意以下内容对我来说100%正常

    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";
    

    导致:

    Id  Balance
    1   1
    2   2
    3   3
    4   4
    5   5
    6   6