2011-12-31 65 views
8

我不知道我的代碼有什麼問題。使用其他如果在sql觸發器時出錯

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$$ 

上述版本不起作用。它說「END」(最後一行)附近的語法錯誤。但是,當我使用的東西有效

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$$ 

我不知道爲什麼。我錯過了什麼嗎?

回答

20

而不是ELSE IFMySQL's syntax使用ELSEIF(沒有空格)。

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$$ 

儘管您可能能夠通過增加一個額外END IF,使其與空間ELSE IF工作。通過使用該空間,可以有效地啓動第二個IF語句,該語句必須獨立於第一個外部IF語句而關閉。

/* 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$$ 
+0

添加鏈接,語法:-) http://dev.mysql.com/doc/refman/5.5/en/if-statement.html – 2011-12-31 02:51:12

+0

@AdrianCornish由於它已經在那裏掛的話「 MySQL的語法「 – 2011-12-31 02:52:31

+0

我的歉意 - 我沒有點擊鏈接 – 2011-12-31 02:55:20