Search code examples
mysqlif-statementtriggersdelimiterdelete-operator

Syntax Error in Mysql Delete Trigger with conditions


I have written a small trigger function in MySQL . This is the trigger query i have written and give syntax error in code.

Error :

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 '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 ;

Solution

  • Syntax of DELETE query, from MySQL documentation is:

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

    Change your DELETE lines in the trigger to:

    DELETE FROM customer_plans WHERE customer_plan_id = first_id;
    

    Sidenote: Based on my personal experience, it is a good habit to DECLARE default values for the variables. eg:

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