【问题标题】:Syntax Error in Mysql Delete Trigger with conditions带有条件的Mysql删除触发器中的语法错误
【发布时间】:2018-09-11 06:31:58
【问题描述】:

我在 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 ;

【问题讨论】:

  • 应该是DELETE FROM customer_plans
  • 不工作它给出了同样的错误@MadhurBhaiya
  • 您能否提供一个 SQL 小提琴,或编辑您的问题以提供表结构(仅触发器中的相关字段)
  • 另外,尝试去掉删除查询中的`?
  • 还是报同样的错误

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


【解决方案1】:

DELETE 查询的语法,来自MySQL documentation 是:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 2015-06-02
    • 1970-01-01
    相关资源
    最近更新 更多