1

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

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 行的 '' 附近。

根据错误消息,我的课程代码声明有问题。但我无法找出问题所在。

提前致谢

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

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$$
4

3 回答 3

1

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

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

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

于 2012-08-21T15:52:12.727 回答
0

您需要确保不会从SELECT.

尝试:

SET curriculum_code = (SELECT code FROM sch_curriculum WHERE id=NEW.id LIMIT 1); 
于 2012-08-21T15:52:21.537 回答
0

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

于 2012-08-21T15:52:51.180 回答