Adding MySQL Trigger: invisible (to me) Syntax Err

2019-09-19 19:34发布

问题:

NOTE:
I initially thought my problem had to do with CONCAT, but since the exact error persisted even when I completely eliminated CONCAT from my query, I figured I should completely over-write of my original post.


I'm trying to set a trigger, and keep getting a Syntax Error.
When I tried this

CREATE TRIGGER set_aka_name 
BEFORE INSERT ON sandbox_person
FOR EACH ROW
BEGIN
  IF (NEW.aka IS NULL) THEN
    SET NEW.aka = 'test value';
  END IF;
END

...I got this error:

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 6


And when trying this (without the IF peren's)

CREATE TRIGGER set_aka_name 
BEFORE INSERT ON sandbox_person
FOR EACH ROW
BEGIN
  IF NEW.aka IS NULL THEN
    SET NEW.aka = 'test value';
  END IF;
END

...I get the same exact error

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 6


It's got to be something simple ... but I'm just not seeing it.
I'm on MySQL 5.1.36.
What am I missing?
Any pointers?

回答1:

try to change delimiter first:

DELIMITER |

CREATE TRIGGER set_aka_name 
BEFORE INSERT ON sandbox_person
FOR EACH ROW
BEGIN
  IF NEW.aka IS NULL THEN
    SET NEW.aka = 'test value';
  END IF;
END|

DELIMITER ;

Maybe MySQL sees the first ";" as the end of CREATE TRIGGER



回答2:

try this:

CREATE TRIGGER set_aka_name 
BEFORE INSERT ON sandbox_person
FOR EACH ROW
BEGIN
  IF NEW.aka IS NULL THEN
    NEW.aka = CONCAT(NEW.fname, ' ', NEW.lname);
  END IF;
END

there is a difference between IF () function and IF statement (see this)