如果触发器中为null,则设置变量

时间:2014-01-18 15:10:14

标签: mysql sql triggers

我有一个类别表,其中“order”列用于排序类别。 我试图在插入之前在触发器中逐步设置顺序:

CREATE TRIGGER `categories_set_order` BEFORE INSERT ON `categories` FOR EACH ROW BEGIN
    DECLARE max_order INT DEFAULT 0;
    SELECT MAX(categories.order) INTO max_order FROM categories;
    SET NEW.order = max_order + 1;
END;

但是如果db中没有记录,则将order列设置为NULL。 我修改了触发器代码:

CREATE TRIGGER `categories_set_order` BEFORE INSERT ON `categories` FOR EACH ROW BEGIN
    DECLARE max_order INT DEFAULT 0;
    SELECT MAX(categories.order) INTO max_order FROM categories;
    IF (ISNULL(@max_order)) THEN BEGIN
        SET max_order = 0;
    END;

    SET NEW.order = max_order + 1;
END;

And I'm getting the following error:
Error Code: 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 9

第9行是:

IF(ISNULL(@max_order))那么开始

我试图删除“@”,但仍然遇到同样的错误。如何解决?

2 个答案:

答案 0 :(得分:6)

您需要更改分隔符。否则,数据库会认为您的触发器定义在第一个;处结束,这将是不完整的。

同时从BEGIN语句中移除IF并添加使用END IF以结束IF

delimiter |
CREATE TRIGGER `categories_set_order` BEFORE INSERT ON `categories` 
FOR EACH ROW BEGIN
    DECLARE max_order INT DEFAULT 0;
    SELECT MAX(categories.order) INTO max_order FROM categories;
    IF (ISNULL(@max_order)) THEN
        SET max_order = 0;
    END IF;

    SET NEW.order = max_order + 1;
END
|
delimiter ;

答案 1 :(得分:2)

除了分隔符,你需要一个END IF

DELIMITER // 
CREATE TRIGGER `categories_set_order` BEFORE INSERT ON `categories` FOR EACH ROW BEGIN
    DECLARE max_order INT DEFAULT 0;
    SELECT MAX(categories.order) INTO max_order FROM categories;
    IF (ISNULL(@max_order)) THEN 
        SET max_order = 0;
    END IF;   
    SET NEW.order = max_order + 1;
END; //
DELIMITER ;