【问题标题】:Why getting a Syntax error in MySQL Trigger query?为什么在 MySQL 触发器查询中出现语法错误?
【发布时间】:2020-02-09 16:26:15
【问题描述】:

我学过 Oracle SQL 中的触发器,但对 MySQL 不太熟悉。我试图将触发命令从 Oracle 转换为 MySQL。首先,我找不到when 语句,而是找到了if else。这是我写的:

create trigger overdraft 
after update on account
for each row 
begin
    if account.balance < 0 then
        insert into borrower(select customer_name, account_number from depositor where new.account_number=depositor.account_number);
        insert into loan(select new.account_number, new.branch_name, new.balance);
        update account set balance = 0 where account.account_number = new.account_number;
    end if;
end;

但是我得到三个语法错误,首先是在左括号的第一个插入语句的末尾,说“语句不完整,期待:','”。另外两个在每个ends 上说“结束在这个位置无效:期待开始,EOF,......”。我的代码有什么问题?我很难弄清楚。

【问题讨论】:

  • 在 mysql 中,您无法操作触发触发器的表 - 在本例中为帐户。您可以调整新的。前触发器中的值。你需要重新考虑你的方法

标签: mysql sql triggers


【解决方案1】:

有几件事。 delimiter 可能就是其中之一:

delimiter $$

create trigger overdraft before update on account
for each row 
begin
    if new.balance < 0 then
        insert into borrower (customer_name, account_number)  -- column list here
            select d.customer_name, d.account_number
            from depositor d
            where new.account_number = d.account_number;

        insert into loan (account_number, branch_name, balance)  -- column list here
            select new.account_number, new.branch_name, new.balance;

        set new.balance = 0;
    end if;
end;$$

delimiter ;

注意事项:

  • delimiter 是必需的,因此触发器的定义不会以第一个分号结束。
  • 初始if (account.balance) 中的引用无法理解,因为account 未定义。
  • 您想使用触发器更新行中的余额。因此,您需要 before update 触发器,而不是 after update 触发器。
  • 向表中插入行时,应始终列出要插入的列。我已经推测了上面的列名。

【讨论】:

    【解决方案2】:

    像这样简单地使用分隔符。

    我以为你已经测试了所有的插入。 Inser ino 必须与我编写的示例类似,但列名可能不同。

    正如我所描述的,您不能在触发触发器的触发器中使用同一个表。所以使用 set 参数将 balance 更改为 0

    DELIMItER //
    create trigger overdraft 
    after update on account
    for each row 
    begin
        if account.balance < 0 then
            insert into borrower (customer_name, account_number) select customer_name, account_number from depositor
             where new.account_number=depositor.account_number;
            insert into loan (account_number, branch_name, balance) select new.account_number, new.branch_name, new.balance;
            set new.balance = 0;
        end if;
    end;
    DELIMItER ;
    

    【讨论】:

    • 在 mysql 中你不能操作触发触发器的表
    • P.三文鱼是对的,您不能更新帐户表,因为这会再次触发,女巫会以永恒的循环结束
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    相关资源
    最近更新 更多