MySQL在触发错误中声明变量

时间:2012-08-21 15:49:04

标签: mysql triggers

有人知道我的触发器声明有什么问题吗?

CREATE TRIGGER `sch_trigger_curriculum_subject_before_insert` BEFORE INSERT ON  
`sch_curriculum_subject` FOR EACH ROW 
BEGIN
   DECLARE curriculum_code VARCHAR(50);        
   SET curriculum_code = SELECT code FROM sch_curriculum WHERE id=NEW.id;
   SET NEW.`code_name` = CONCAT(curriculum_code,' - ', NEW.code,' - (',NEW.name,')');
END;

错误:SQL错误(1064):您的SQL语法错误.....在第4行附近。

根据错误消息,我的curriculum_code声明有问题。但我不知道出了什么问题。

提前致谢

更新 已经解决,问题是分隔符,这是工作的

DELIMITER $$
CREATE TRIGGER `sch_trigger_curriculum_subject_before_insert` BEFORE INSERT ON  
`sch_curriculum_subject` FOR EACH ROW 
BEGIN
  DECLARE curriculum_code VARCHAR(50);        
  SET curriculum_code = (SELECT code FROM sch_curriculum WHERE id=NEW.id);
  SET NEW.`code_name` = CONCAT(curriculum_code,' - ', NEW.code,' - (',NEW.name,')');
END$$

3 个答案:

答案 0 :(得分:1)

您不能以这种方式为变量分配SELECT语句。至少你应该将SELECT语句放在括号中以将其作为子查询执行,但更好的是:

SELECT code FROM sch_curriculum WHERE id = NEW.id INTO curriculum_code;

请注意,查询不会返回多条记录(假设UNIQUE列中存在id约束,因此这可能不是问题。)

答案 1 :(得分:0)

您需要确保不会从SELECT返回多个值。

尝试:

SET curriculum_code = (SELECT code FROM sch_curriculum WHERE id=NEW.id LIMIT 1); 

答案 2 :(得分:0)

你不能简单地SET curriculum_code = some_SQL。我怀疑你的意思是SELECT ... INTO curriculum_code