创建SQL触发器以更新行值

时间:2016-08-04 00:29:47

标签: mysql database-trigger

我有一个SQL表“收件箱”,其中包含“modem_id”和“user”列 我想在modem_id为1时创建一个SQL触发器,“user”列正在插入值'A'; 2为用户'B'...

我用if else创建了一个SQL触发器:

delimiter //
CREATE TRIGGER upd_user_inbox BEFORE insert ON inbox
    FOR EACH ROW
    BEGIN
    IF NEW.modem_id = 0 THEN
             UPDATE `inbox` SET `user` = 'A' WHERE modem_id = 1; 
         ELSEIF NEW.modem_id = 2 THEN
             UPDATE `inbox` SET `user` = 'B' WHERE modem_id = 2; 
            ELSEIF NEW.modem_id = 3 THEN
             UPDATE `inbox` SET `user` = 'C' WHERE modem_id = 3; 
            ELSEIF NEW.modem_id = 4 THEN
             UPDATE `inbox` SET `user` = 'D' WHERE modem_id = 4; 
            ELSEIF NEW.modem_id = 5 THEN
             UPDATE `inbox` SET `user` = 'E' WHERE modem_id = 5; 
            ELSEIF NEW.modem_id = 6 THEN
             UPDATE `inbox` SET `user` = 'F' WHERE modem_id = 6; 
            ELSEIF NEW.modem_id = 7 THEN
             UPDATE `inbox` SET `user` = 'G' WHERE modem_id = 7; 
            ELSEIF NEW.modem_id = 8 THEN
             UPDATE `inbox` SET `user` = 'H' WHERE modem_id = 8; 
         END IF;
     END;//
delimiter ;

触发器成功执行但无法正常工作。 如果'if-else'不起作用,任何人都可以教我使用'case'而不是吗?

谢谢

1 个答案:

答案 0 :(得分:0)

https://dev.mysql.com/doc/refman/5.7/en/case.html

CASE NEW.modem_id
WHEN 0 THEN ...
WHEN 2 THEN ...
...
END CASE