Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error when using else if in sql trigger

I am not sure whats wrong with my code.

 delimiter $$
 CREATE TRIGGER updateRestaurantAtributes 
 AFTER UPDATE ON fields_data
 FOR EACH ROW BEGIN
 IF (NEW.fieldid = 1) THEN
    UPDATE restaurants
    SET address1 = NEW.data_txt 
    Where rid = NEW.itemid;
 ELSE IF (NEW.fieldid = 2) THEN
    UPDATE restaurants
    SET address2 = NEW.data_txt 
    Where rid = NEW.itemid;
 END IF;
END$$

The above version does not work. It says syntax error near "END"(Last line). But the something works when I use

delimiter $$
CREATE TRIGGER updateRestaurantAtributes 
AFTER UPDATE ON fields_data
FOR EACH ROW BEGIN
IF (NEW.fieldid = 1) THEN
    UPDATE restaurants
    SET address1 = NEW.data_txt 
    Where rid = NEW.itemid;
END IF;
IF (NEW.fieldid = 2) THEN
    UPDATE restaurants
    SET address2 = NEW.data_txt 
    Where rid = NEW.itemid;
END IF;
END$$

I am not sure why. Am I missing something?

like image 423
user899893 Avatar asked Dec 31 '11 02:12

user899893


1 Answers

Instead of ELSE IF, MySQL's syntax uses ELSEIF (without the space).

 delimiter $$
 CREATE TRIGGER updateRestaurantAtributes 
 AFTER UPDATE ON fields_data
 FOR EACH ROW BEGIN
 IF (NEW.fieldid = 1) THEN
    UPDATE restaurants
    SET address1 = NEW.data_txt 
    Where rid = NEW.itemid;
 ELSEIF (NEW.fieldid = 2) THEN
    UPDATE restaurants
    SET address2 = NEW.data_txt 
    Where rid = NEW.itemid;
 END IF;
END$$

Although you might be able to make it work with the space in ELSE IF by adding an additional END IF. By using the space, you effectively initiate a second IF statement, which must be closed independently of the first outer IF statement.

/* Might work */
delimiter $$
 CREATE TRIGGER updateRestaurantAtributes 
 AFTER UPDATE ON fields_data
 FOR EACH ROW BEGIN
 IF (NEW.fieldid = 1) THEN
    UPDATE restaurants
    SET address1 = NEW.data_txt 
    Where rid = NEW.itemid;
 /* Opens a seconds IF block which must be closed */
 ELSE IF (NEW.fieldid = 2) THEN
    UPDATE restaurants
    SET address2 = NEW.data_txt 
    Where rid = NEW.itemid;
  /* Close inner IF block */
  END IF;
 END IF;
END$$
like image 58
Michael Berkowski Avatar answered Sep 18 '22 11:09

Michael Berkowski