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 :-)

JNK
  • 63,321
  • 15
  • 122
  • 138
Georg Ledermann
  • 2,712
  • 4
  • 31
  • 35
  • 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 '09 at 16:24
  • I'm making this a comment not an answer because it's a guess :p – Greg Jan 22 '09 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... – Georg Ledermann Jan 22 '09 at 16:28

1 Answers1

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 ;
Greg
  • 316,276
  • 54
  • 369
  • 333