2010-06-05 76 views
2

如何創建SQLite觸發器來計算「實際」表上的運行總數?以下SQL代碼應更新AccountBalances表,以便餘額列從1,2,3,... rowcount開始計數。但是,即使啓用了recursive_triggers,觸發器也只會更新第二行。以下結果是第1行= 1,第2行= 2,之後的行爲空。使用觸發器計算SQLite表中的運行總數

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 

回答

0
  1. 請檢查SQLITE_MAX_TRIGGER_DEPTH值。它可以設置爲1而不是默認值1000嗎?

  2. 請檢查您的SQLite版本。在3.6.18之前,遞歸觸發器不被支持。

請注意,以下爲我工作的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 
+0

你說得對,我的SQLite版。它不起作用,因爲我使用了Firefox的SQLite Manager 0.5.15插件。它在我使用官方的sqlite3.exe時起作用。 – 2010-06-05 02:54:07

+0

當我將它用於超過1000行的表格時,看起來我得到了「錯誤:觸發器遞歸的級別過多」。我將不得不以另一種方式實施運行總計。 – 2010-06-05 03:47:05