我正在尝试创建一个mysql触发器。错误代码1064非常通用。触发器是查看特定键是否存在记录;如果它确实使用该值更新新插入的行中的特定列。我在触发器打开的同一个表上使用选择查询。这会导致问题吗?这是代码:
DELIMITER $$
CREATE TRIGGER classid_insert
AFTER INSERT ON courses_semester
FOR EACH ROW
BEGIN
SET @class_id = (SELECT class_id FROM courses_semester WHERE
course_id = NEW.`course_id`
AND `dept_id` = NEW.`dept_id`
AND `univ_id` = NEW.`univ_id`
AND `section_id` = NEW.`section_id`
AND `semester` = NEW.`semester`
AND `year` = NEW.`year`);
IF(@class_id = NULL)
THEN
NEW.class_id = UUID()
ELSE
NEW.class_id = @class_id
END IF;
END
DELIMITER ;
答案 0 :(得分:0)
您的整个触发器代码应如下所示。删除DELIMITER $$
之后和DELIMITER ;
之前的空格。此外,最后END
需要更改为END $$
。此外,它必须是BEFORE
触发器,而不是AFTER
触发器。
此外,NEW.class_id = UUID()
不正确。它缺少SET
SET NEW.class_id = UUID();
正确的触发代码:
DELIMITER $$
CREATE TRIGGER classid_insert
BEFORE INSERT ON courses_semester
FOR EACH ROW
BEGIN
SET @class_id = (SELECT class_id FROM courses_semester WHERE
course_id = NEW.`course_id`
AND `dept_id` = NEW.`dept_id`
AND `univ_id` = NEW.`univ_id`
AND `section_id` = NEW.`section_id`
AND `semester` = NEW.`semester`
AND `year` = NEW.`year`);
IF(@class_id = NULL)
THEN
SET NEW.class_id = UUID();
ELSE
SET NEW.class_id = @class_id;
END IF;
END $$
DELIMITER ;