Search code examples
mysqldatabasetriggersmysql-error-1064

MySQL syntax Error on Create Trigger


Here is my trigger, I am getting the MySQL syntax error. I wanted to reduce the balance from sms_index table sms_count column value.

 CREATE TRIGGER sms_log_update AFTER UPDATE ON sms_index
  FOR EACH ROW
  BEGIN
    IF NEW.approved_status = '1' THEN
      UPDATE  sms_package SET  balance =  (balance - OLD.sms_count) WHERE  group_id = OLD.ins_group_id;
    END IF;
  END;

Error Message:

 #1064 - 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 '' at line 5 

Solution

  • Your code looks correct, except for the possible problem of the delimiter. Try the following:

    DELIMITER //
    CREATE TRIGGER sms_log_update AFTER UPDATE ON sms_index
    FOR EACH ROW
    BEGIN
        IF NEW.approved_status = '1' THEN
            UPDATE  sms_package SET  balance =  (balance - OLD.sms_count)
            WHERE  group_id = OLD.ins_group_id;
        END IF;
    END;//
    
    DELIMITER ;
    

    From the documentation:

    However, just as for stored routines, if you use the mysql program to define a trigger that executes multiple statements, it is necessary to redefine the mysql statement delimiter so that you can use the ; statement delimiter within the trigger definition.