错误mysql语法触发器

时间:2017-06-29 12:10:14

标签: mysql triggers

根据phpmyadmin,我在此触发器中出现语法错误:

CREATE TRIGGER insert_device
AFTER INSERT ON table_e
FOR EACH ROW

BEGIN

DECLARE m_id_a INTEGER;
DECLARE m_id_d INTEGER;
m_id_d := 0;

SELECT id_a INTO m_id_a FROM table_ua WHERE ua_eui = NEW.eui LIMIT 1;

SELECT id_d INTO m_id_d FROM table_d WHERE d_idapp = m_id_a ORDER BY id asc LIMIT 1;
IF (m_id_d == 0) THEN
    INSERT INTO table_d (d_addr, d_eui, d_apps, d_nwks, d_idapp)
    VALUE (NEW.addr, NEW.eui, NEW.apps, NEW.nwks, m_id_a);
ELSE
    UPDATE TABLE table_d
    SET
      d_addr = NEW.addr,
      d_eui = NEW.eui,
      d_apps = NEW.apps,
      d_nwks = NEW.nwks
    WHERE id_d = m_id_d;
END IF;

END

错误是:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':= 0;

错误是什么?我不明白我做错了什么..

感谢。

1 个答案:

答案 0 :(得分:1)

触发器中存在多个语法错误:

  1. declare变量,您应该使用set;
  2. 调用它
  3. IF表达式不能使用==,只有一个是正确的;
  4. update语法只需指定表名称UPDATE table_d SET ...
  5. 所以请尝试以下触发器:

    delimiter $$
    CREATE TRIGGER insert_device
    AFTER INSERT ON table_e
    FOR EACH ROW
    
    BEGIN
    
    DECLARE m_id_a INTEGER;
    DECLARE m_id_d INTEGER;
    set m_id_d = 0;
    SELECT id_a INTO m_id_a FROM table_ua WHERE ua_eui = NEW.eui LIMIT 1;
    
    SELECT id_d INTO m_id_d FROM table_d WHERE d_idapp = m_id_a ORDER BY id asc LIMIT 1;
    IF (m_id_d = 0) THEN
        INSERT INTO table_d (d_addr, d_eui, d_apps, d_nwks, d_idapp)
        VALUE (NEW.addr, NEW.eui, NEW.apps, NEW.nwks, m_id_a);
    ELSE
        UPDATE table_d
        SET
          d_addr = NEW.addr,
          d_eui = NEW.eui,
          d_apps = NEW.apps,
          d_nwks = NEW.nwks
        WHERE id_d = m_id_d;
    END IF;
    
    END
    $$