MySQL创建触发器语法

时间:2013-12-21 20:37:40

标签: mysql sql syntax triggers

DELIMITER // 
CREATE TRIGGER never_update_with_null
BEFORE UPDATE
ON `table_name`
FOR EACH ROW
BEGIN
    IF OLD.name IS NOT NULL AND NEW.name IS NULL THEN
        SET NEW.name = OLD.name;
    IF OLD.phone IS NOT NULL AND NEW.name IS NULL THEN
        SET NEW.phone = OLD.phone;
    IF OLD.place IS NOT NULL AND NEW.place IS NULL THEN
        SET NEW.place = OLD.place;
END; //
DELIMITER ;

我正在努力实现以下目标: 如果某个UPDATE中的namephoneplace(列)中的某个值table_name及其值(更新值)为{{1}然后该值保持旧值(不会更新)。 也许更短一点:永远不要用NULL更新。

上面的SQL不会创建触发器,但它不会抛出任何错误(phpMyAdmin)。它缺乏语法吗?在NULL之后已经使用ENDIF;进行了尝试 - 没有任何改进。谢谢你的解释。

1 个答案:

答案 0 :(得分:3)

尝试

DELIMITER // 
CREATE TRIGGER never_update_with_null
BEFORE UPDATE
ON `table_name`
FOR EACH ROW
BEGIN
    IF OLD.name IS NOT NULL AND NEW.name IS NULL THEN
        SET NEW.name = OLD.name;
    END IF;
    IF OLD.phone IS NOT NULL AND NEW.phone IS NULL THEN
        SET NEW.phone = OLD.phone;
    END IF;
    IF OLD.place IS NOT NULL AND NEW.place IS NULL THEN
        SET NEW.place = OLD.place;
    END IF;
END; //
DELIMITER ;