Search code examples
mysqltriggerssyntax-errormysql-workbenchmysql-error-1064

MySQL Trigger IF syntax error


I was creating some triggers (using MySQL Workbench), and got an error regarding the if statement in one of them. Here it is:

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 tells me

"missing 'end'" at line 6 (where the 'end if;' is),

and phpMyAdmin tells me

"#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".

I'm really stuck on this, so I'd be really happy if someone could help me, I've searched for the IF syntax on the web, but I don't see anything wrong...


Solution

  • Okay, problem solved.

    First, I needed to use delimiters to avoid the error near end if;.

    For the next error, MySQL requires declare statements to be put next to the begin, thanks to this post I found the answer. Thanks !