创建一个SQLite触发器,根据插入时的事务信息更新银行帐户

时间:2014-12-09 05:52:16

标签: android sql database sqlite triggers

我有一个Android应用程序,可以帮助用户跟踪他们的财务状况。该应用程序具有存储帐户和交易信息的数据库。每次记录交易时,我还必须更新帐户表以调整该帐户的余额,以及它在特定支出期间的剩余免税额。帐户表如下所示:

| id | name | balance | allowance | allowanceRemaining | spendingPeriod |

一个看起来像这样的交易表:

| id | description | amount | withdrawal | discretionary | accountID |

撤回和自由裁量权都是0或1的整数作为布尔值。我已经尝试了以下内容,至少根据交易是否撤销来设置余额,但我收到语法错误,我无法弄清楚原因。但是,除了语法之外,我无法理解逻辑并创建了正确的案例陈述。

CREATE TRIGGER update_account AFTER INSERT ON transactions
BEGIN
  UPDATE accounts a SET a.balance = 
    (CASE WHEN new.withdrawal = 1 THEN a.balance - new.amount ELSE
     a.balance + new.amount END) WHERE a.id = new.accountID;
END;

在伪代码中,我想做的是:

  • 如果交易是存款,请加钱
  • 如果交易是提款,请检查是否是自行决定
  • 如果是酌情决定,则从余额中扣除并留出余额
  • 如果不是,请仅从余额中删除。

我制作了一个SQL Fiddle,它有一些快速的样本数据但没有触发器。

1 个答案:

答案 0 :(得分:1)

UPDATE需要每个更改列的新值,因此您必须以这种方式制定您的要求:

余额

  • 增加了存款金额,
  • 减少提款金额。

剩余免税额

  • 减少了一次意外撤回的数额。

至于语法,您不能使用UPDATEd表的别名:

CREATE TRIGGER update_account
AFTER INSERT ON transactions
BEGIN
    UPDATE accounts
    SET balance = CASE
                  WHEN new.withdrawal THEN balance - new.amount
                  ELSE                     balance + new.amount
                  END,
        allowanceRemaining = CASE
                             WHEN new.withdrawal AND new.discretionary
                             THEN allowanceRemaining - new.amount
                             ELSE allowanceRemaining
                             END
    WHERE id = NEW.accountID;
END;

使用触发器的WHEN子句可能更简单:

CREATE TRIGGER update_balance_for_deposit
AFTER INSERT ON transactions
WHEN NOT NEW.withdrawal
BEGIN
    UPDATE accounts
    SET balance = balance + NEW.amount
    WHERE id = NEW.accountID;
END;

CREATE TRIGGER update_balance_for_withdrawal
AFTER INSERT ON transactions
WHEN NEW.withdrawal
BEGIN
    UPDATE accounts
    SET balance = balance - NEW.amount
    WHERE id = NEW.accountID;
END;

CREATE TRIGGER update_allowance_for_discretionary_withdrawal
AFTER INSERT ON transactions
WHEN NEW.withdrawal AND NEW.discretionary
BEGIN
    UPDATE accounts
    SET allowanceRemaining = allowanceRemaining - NEW.amount
    WHERE id = NEW.accountID;
END;