Adding MySQL Trigger: invisible (to me) Syntax Error

空扰寡人 提交于 2019-12-13 08:26:43

问题


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)



来源:https://stackoverflow.com/questions/12943785/adding-mysql-trigger-invisible-to-me-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!