带有条件的Mysql删除触发器中的语法错误

时间:2018-09-11 06:31:58

标签: mysql if-statement triggers delimiter delete-operator

我已经在MySQL中编写了一个小的触发函数。这是我编写的触发器查询,并在代码中给出语法错误。

错误:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本以使用正确的语法   在'cp WHERE cp附近。customer_plan_id = first_id;

DELIMITER $$
CREATE TRIGGER delete_plan_on_delete_customer 
    AFTER DELETE ON customers
    FOR EACH ROW 
BEGIN
    DECLARE active_plan INT;
    DECLARE first_id INT;

    SET active_plan = (SELECT is_active
    FROM customer_plans 
    WHERE customer_id=OLD.customer_id AND first_plan_id=1);

    if(active_plan = 0)THEN

        SET first_id = (SELECT customer_plan_id
        FROM customer_plans 
        WHERE customer_id=OLD.customer_id AND first_plan_id=1);

        DELETE customer_plans cp WHERE `cp`.`customer_plan_id`= first_id;
   END IF; 
END$$
DELIMITER ;

1 个答案:

答案 0 :(得分:0)

来自MySQL documentationDELETE查询的语法是:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
    [PARTITION (partition_name [, partition_name] ...)]
    [WHERE where_condition]
    [ORDER BY ...]
    [LIMIT row_count]

将触发器中的DELETE行更改为:

DELETE FROM customer_plans WHERE customer_plan_id = first_id;

边注:根据我的个人经验,DECLARE变量的默认值是一个好习惯。例如:

DECLARE active_plan INT(11) DEFAULT 0;
DECLARE first_id INT(11) DEFAULT 0;