创建触发器时的 SQLite 条件

SQLite conditionals in creation of a trigger

我正在使用 SQLite 创建触发器,我想比较旧值是否与新值不同,以便我可以执行 INSERT

这是我创建的触发器,但似乎 MySQL 语法在 SQLite 中不起作用。 什么是等效的?

CREATE TRIGGER document_handler AFTER UPDATE ON document
FOR EACH ROW
BEGIN
    IF NEW.type <> OLD.type THEN
        INSERT INTO DocumentUpdates (id_document, attribute_changed, lastvalue, newvalue, modification_date)
        VALUES (id, "type", OLD.type, NEW.type, NOW());
    END IF;
    
    IF NEW.title <> OLD.title THEN
        INSERT INTO DocumentUpdates (id_document, attribute_changed, lastvalue, newvalue, modification_date)
        VALUES (id, "title", OLD.title, NEW.title, NOW());
    END IF;
    
    IF NEW.path <> OLD.path THEN
        INSERT INTO DocumentUpdates (id_document, attribute_changed, lastvalue, newvalue, modification_date)
        VALUES (id, "path", OLD.path, NEW.path, NOW());
    END IF;
END;

在 SQLite 中没有 IF 条件语句。

在这种情况下,您可以使用简单的 WHERE 子句:

CREATE TRIGGER document_handler AFTER UPDATE ON document
FOR EACH ROW
BEGIN
  INSERT INTO DocumentUpdates (id_document, attribute_changed, lastvalue, newvalue, modification_date)
  SELECT NEW.id, 'type', OLD.type, NEW.type, CURRENT_TIMESTAMP
  WHERE NEW.type IS NOT OLD.type;

  INSERT INTO DocumentUpdates (id_document, attribute_changed, lastvalue, newvalue, modification_date)
  SELECT NEW.id, 'title', OLD.title, NEW.title, CURRENT_TIMESTAMP
  WHERE NEW.title IS NOT OLD.title;
    
  INSERT INTO DocumentUpdates (id_document, attribute_changed, lastvalue, newvalue, modification_date)
  SELECT NEW.id, 'path', OLD.path, NEW.path, CURRENT_TIMESTAMP
  WHERE NEW.path IS NOT OLD.path;
END;

我将所有 <> 更改为 IS NOT,它也可以比较 NULL 值。
此外,SQLite 中 NOW() 的等价物是 CURRENT_TIMESTAMP.

查看简化版 demo.