我不确定我的代码有什么问题。
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$$
我不确定为什么。我错过了什么吗?
答案 0 :(得分:23)
而不是ELSE IF
,MySQL'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$$
虽然您可以通过添加额外的ELSE IF
来使其与END 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$$
答案 1 :(得分:0)
在Mysql Workbench 8.0中,单击表旁边的设置图标,然后在其中找到触发器选项卡。根据您的要求创建触发器,遵循if-else语法将完美地工作
CREATE DEFINER=`root`@`localhost` TRIGGER `users_AFTER_INSERT` AFTER INSERT ON `users` FOR EACH ROW BEGIN
IF (NEW.status_active = 1) THEN
UPDATE broadcast_status SET `type` = 0, `status` = 0 WHERE user_id = NEW.id;
ELSE
IF (NEW.status_active = 2) THEN
UPDATE broadcast_status SET `type` = 0, `status` = 2 WHERE user_id = NEW.id;
ELSE
UPDATE broadcast_status SET `type` = 0, `status` = 1 WHERE user_id = NEW.id;
END IF;
END IF;
END