Search code examples
mysqlsqldatabasetriggersmysql-error-1064

Getting 1064 error while creating mysql trigger


I am trying to create mysql trigger but getting an error

Error #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 14

Here is my sql script

delimiter $$
CREATE TRIGGER `update_account_balance_after_transfer` AFTER INSERT ON `balance_transfer`
 FOR EACH ROW  
    BEGIN
    IF(NEW.from_account_type='CUSTOMER') THEN
        UPDATE customer c SET c.balance = c.balance-NEW.amount WHERE c.customer_id= NEW.from_account_id;
    ELSE IF(NEW.from_account_type='Vendor') THEN
        UPDATE vendor V SET v.balance = v.balance-NEW.amount WHERE v.vendor= NEW.from_account_id;
    END IF;
    IF(NEW.to_account_type='VENDOR') THEN
        UPDATE customer c SET c.balance = c.balance+NEW.amount WHERE c.customer_id= NEW.to_account_id;
    ELSE IF(NEW.to_account_type='Vendor') THEN
        UPDATE vendor V SET v.balance = v.balance+NEW.amount WHERE v.vendor= NEW.to_account_id;
    END IF;
END $$
delimiter ;

Solution

  • Remove space between ELSE and IF. It should be ELSEIF as below.

    delimiter $$
    CREATE TRIGGER `update_account_balance_after_transfer` AFTER INSERT ON `balance_transfer`
     FOR EACH ROW  
        BEGIN
        IF(NEW.from_account_type='CUSTOMER') THEN
            UPDATE customer c SET c.balance = c.balance-NEW.amount WHERE c.customer_id= NEW.from_account_id;
        ELSEIF(NEW.from_account_type='Vendor') THEN
            UPDATE vendor V SET v.balance = v.balance-NEW.amount WHERE v.vendor= NEW.from_account_id;
        END IF;
        IF(NEW.to_account_type='VENDOR') THEN
            UPDATE customer c SET c.balance = c.balance+NEW.amount WHERE c.customer_id= NEW.to_account_id;
        ELSEIF(NEW.to_account_type='Vendor') THEN
            UPDATE vendor V SET v.balance = v.balance+NEW.amount WHERE v.vendor= NEW.to_account_id;
        END IF;
    END $$
    delimiter ;
    

    MySQL IF Syntax

    Check the demo here