创建触发器时出现语法错误

时间:2012-07-29 16:08:57

标签: mysql sql

我正在尝试在MySQL中创建一个新的触发器,但无论我尝试什么,我都会遇到语法错误。我想在html_id列中插入一个值,该列是字母f和列id的串联:

CREATE TRIGGER htmlid 
BEFORE INSERT ON makelist_food
FOR EACH ROW
BEGIN
  IF (NEW.html_id IS NULL) THEN
  NEW.html_id = CONCAT('f', NEW.id);
  END IF;
END

我也试过这个:

CREATE TRIGGER htmlid 
BEFORE INSERT ON makelist_food
FOR EACH ROW
BEGIN
  IF (NEW.html_id IS NULL) THEN
  INSERT INTO makelist_food SET html_id = CONCAT('f', NEW.id);
  END IF;
END

这个(更改分隔符):

DELIMITER $$

CREATE TRIGGER htmlid 
BEFORE INSERT ON makelist_food
FOR EACH ROW
BEGIN
  IF (NEW.html_id IS NULL) THEN
  NEW.html_id = CONCAT('f', NEW.id);
  END IF;
END$$

DELIMITER ;

我得到的错误:#1064 - 您的SQL语法出错;检查与您的MySQL服务器版本相对应的手册,以便在第6行的'.html_id = CONCAT('f',NEW.id)附近使用正确的语法

我正在运行MySQL 5.5.22。

2 个答案:

答案 0 :(得分:2)

尝试使用此查询:

delimiter |

    CREATE TRIGGER htmlid 
    BEFORE INSERT ON makelist_food
    FOR EACH ROW
    BEGIN
      IF (NEW.html_id IS NULL) THEN
      INSERT INTO makelist_food SET html_id = CONCAT('f', NEW.id);
      END IF;
    END
    |
    delimiter ;

答案 1 :(得分:2)

我认为区别在于SET关键字。试试这个

DELIMITER $$

CREATE TRIGGER htmlid 
BEFORE INSERT ON makelist_food
FOR EACH ROW
BEGIN
  IF (NEW.html_id IS NULL) THEN
     SET NEW.html_id = CONCAT('f', NEW.id);
  END IF;
END$$

DELIMITER ;