在mysql触发器中使用case / if / else时的语法错误

时间:2019-07-09 07:32:30

标签: mysql sql triggers

我在MySQL触发器中使用了case语句。 但是在MySQL的触发器中使用case块/ if / else时会出现语法错误。

使用案例

DELIMITER //
CREATE DEFINER=`root`@`localhost` 
       TRIGGER `color_changed` 
       AFTER INSERT ON `tb_tickets`
       FOR EACH ROW 
BEGIN
 CASE NEW.program_id
 WHEN 1 THEN
   UPDATE tb_sites_1 
   SET color_status = NEW.status 
   WHERE site_id = NEW.site_id;
 WHEN 2 THEN
   UPDATE tb_sites_2 
   SET color_status = NEW.status 
   WHERE site_id = NEW.site_id;
 WHEN 3 THEN
   UPDATE tb_sites_3
   SET color_status = NEW.status 
   WHERE site_id = NEW.site_id;
 END
END
DELIMITER ;

错误  抱歉,发生了意外错误!

使用IF / ELSE

CREATE DEFINER=`root`@`localhost` 
       TRIGGER `color_changed` 
       AFTER INSERT ON `tb_tickets`
       FOR EACH ROW 
BEGIN
 IF NEW.program_id = 1 THEN
   UPDATE tb_sites_1 
   SET color_status = NEW.status 
   WHERE site_id = NEW.site_id;
 ELSEIF NEW.program_id = 2 THEN
   UPDATE tb_sites_2 
   SET color_status = NEW.status 
   WHERE site_id = NEW.site_id;
 ELSE
  UPDATE tb_sites_3
   SET color_status = NEW.status 
   WHERE site_id = NEW.site_id;
 END
END;

错误

#1064-您的SQL语法有误;检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第9行的''附近使用

1 个答案:

答案 0 :(得分:1)

始终最好阅读全文。您错过了最终案例;然后结束//(对于开始)

DELIMITER //
CREATE TRIGGER T
       AFTER INSERT ON `tb_tickets`
       FOR EACH ROW 
BEGIN
 CASE NEW.program_id
 WHEN 1 THEN
   UPDATE tb_sites_1 
   SET color_status = NEW.status 
   WHERE site_id = NEW.site_id;
 WHEN 2 THEN
   UPDATE tb_sites_2 
   SET color_status = NEW.status 
   WHERE site_id = NEW.site_id;
 WHEN 3 THEN
   UPDATE tb_sites_3
   SET color_status = NEW.status 
   WHERE site_id = NEW.site_id;
 END CASE;
END //
DELIMITER ;

如果还有其他错误,请添加完整的错误。