mysql 创建触发器时出现语法错误 1064

mysql syntax ERROR 1064 while creating a trigger

我正在为我的 table 创建触发器:- 银行 银行(pin、存款、取款、余额、accno*、sno) 和 平衡 余额(账户*,余额)

我想在插入银行 table 后更新余额 table 中的余额值。 我正在使用 MySQL 服务器 (wamp64 mysql8.0.18)

mysql> create trigger update_account
    -> after insert on bank
    -> begin
    -> update balance as a
    -> set a.balance=(case
    -> when new.withdraw=1 then a.balance-new.withdraw
    -> else a.balance+new.withdraw
    -> end)
    -> where a.accno = new.accno;

但是上面的代码给我以下错误:- 错误 1064 (42000):您的 SQL 语法有误;查看与您的 MySQL 服务器版本相对应的手册,了解使用 near 'update balance a 的正确语法 设置 a.balance = (案例 当 new.withdraw=1 然后 a.balance - 新。在第 3 行

您应该创建与我的代码相同的触发器查询:

create trigger update_account
    after insert
    on bank
    for each row
begin
    update balance as a
    set a.balance=(IF(new.withdraw = 1, a.balance - new.withdraw, a.balance + new.withdraw))
    where a.accno = new.accno;
END;

如果你只有两种情况,你应该IF,不需要Case when

DELIMITER $$
DROP PROCEDURE my_procedure$$
create trigger update_account
after insert
on bank
for each row
begin
update balance as a
set a.balance= a.balance + new.withdraw + new.deposit
where a.accno=new.accno;
END$$
DELIMITER ;

我的代码现在可以工作了 谢谢大家

您的触发器包含 ONE 语句。所以它不需要在 BEGIN-END 块和 DELIMITER 重新分配:

CREATE TRIGGER update_account
AFTER INSERT
ON bank
FOR EACH ROW
UPDATE balance
SET balance = balance + new.withdraw + new.deposit
where accno=new.accno;