我有一个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,它有一些快速的样本数据但没有触发器。
答案 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;