MySQL Trigger IF语法错误

时间:2015-03-29 13:33:43

标签: mysql triggers syntax-error mysql-workbench mysql-error-1064

我正在创建一些触发器(使用MySQL Workbench),并且在其中一个中出现了关于if语句的错误。这是:

CREATE DEFINER = CURRENT_USER TRIGGER `mydatabase`.`transactions_AFTER_UPDATE` AFTER UPDATE ON `transactions` FOR EACH ROW
begin

if (old.idUser != new.idUser) then
    signal sqlstate '45000' set message_text = "Can't change transactions' initiator.";
end if;
declare oldAmountTokens integer;
SET @oldAmountTokens = (SELECT tokens from offers WHERE idoffer = old.idOffer);
declare newAmountTokens integer;
SET @newAmountTokens = (SELECT tokens from offers WHERE idoffer = new.idOffer);
declare diff integer;
SET @diff = @newAmountTokens - @oldAmountTokens;
UPDATE users SET tokens = users.tokens + @diff WHERE idUser = new.idUser;
end

MySQL Workbench告诉我

"missing 'end'" at line 6(其中'end if;'是),

和phpMyAdmin告诉我

"#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 5".

我真的很困惑,所以如果有人能帮助我,我会很高兴,我在网上搜索了IF语法,但我没有看到任何错误...

2 个答案:

答案 0 :(得分:1)

好的,问题解决了。

首先,我需要使用分隔符来避免end if;附近的错误。

对于下一个错误,MySQL需要将declare语句放在begin的旁边,这要归功于post我找到了答案。谢谢!

答案 1 :(得分:0)

我的触发器代码看起来没问题,虽然我在transactions之后删除了单引号。你有delimiter陈述吗?

delimiter //

CREATE DEFINER = CURRENT_USER TRIGGER `mydatabase`.`transactions_AFTER_UPDATE`
    AFTER UPDATE ON `transactions` FOR EACH ROW
begin
    if (old.idUser <> new.idUser) then
        signal sqlstate '45000' set message_text = "Can't change transactions  initiator.";
    end if;
    declare @oldAmountTokens integer;
    SET @oldAmountTokens = (SELECT tokens from offers WHERE idoffer = old.idOffer);
    declare @newAmountTokens integer;
    SET @newAmountTokens = (SELECT tokens from offers WHERE idoffer = new.idOffer);
    declare @diff integer;
    SET @diff = @newAmountTokens - @oldAmountTokens;
    UPDATE users SET tokens = users.tokens + @diff WHERE idUser = new.idUser;
end//

delimiter ;