17

I have trouble defining a trigger for a MySQL database. I want to change a textfield before inserting a new row (under a given condition). This is what I have tried:

CREATE TRIGGER add_bcc
BEFORE INSERT ON MailQueue
FOR EACH ROW BEGIN
  IF (NEW.sHeaders LIKE "%support@mydomain.com%") THEN
    SET NEW.sHeaders = NEW.sHeaders + "BCC:internal@mydomain.com";
  END IF;
END; 

But always I get the error "wrong syntax". I got stuck, what am I doing wrong? I'm using MySQL 5.0.51a-community

BTW: Creating an empty Trigger like this works fine:

CREATE TRIGGER add_bcc
BEFORE INSERT ON MailQueue
FOR EACH ROW BEGIN
END; 

But this fails, too:

CREATE TRIGGER add_bcc
BEFORE INSERT ON MailQueue 
FOR EACH ROW BEGIN
  IF 1=1 THEN
  END IF; 
END;

It's my first time to use stackoverflow.com, so I'm very excited if it is helpful to post something here :-)

3
  • What happens if you remove "SET"? Also you should change NEW.sHeaders + "BCC:internal@mydomain.com" to CONCAT(NEW.sHeaders, "BCC:internal@mydomain.com")
    – Greg
    Jan 22, 2009 at 16:24
  • I'm making this a comment not an answer because it's a guess :p
    – Greg
    Jan 22, 2009 at 16:24
  • Thanks! I've tried it, but the syntax error seems to be caused by the if statement. Even the following fails: CREATE TRIGGER add_bcc BEFORE INSERT ON MailQueue FOR EACH ROW BEGIN IF 1=1 THEN END IF; END; Sadly, MySQL does not give any good hints what the error is about... Jan 22, 2009 at 16:28

1 Answer 1

29

You need to change the delimiter - MySQL is seeing the first ";" as the end of the CREATE TRIGGER statement.

Try this:

/* Change the delimiter so we can use ";" within the CREATE TRIGGER */
DELIMITER $$

CREATE TRIGGER add_bcc
BEFORE INSERT ON MailQueue
FOR EACH ROW BEGIN
  IF (NEW.sHeaders LIKE "%support@mydomain.com%") THEN
    SET NEW.sHeaders = NEW.sHeaders + "BCC:internal@mydomain.com";
  END IF;
END$$
/* This is now "END$$" not "END;" */

/* Reset the delimiter back to ";" */
DELIMITER ;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.