如何在SQLite触发器中使用WITH子句

时间:2018-06-07 19:31:00

标签: sqlite

我试图在SQLite数据库中创建某些内容的日志。我使用触发器执行此操作,但我需要插入多个日志记录,并且它们都需要具有相同的时间戳。为了做到这一点,我试图使用WITH子句来获取当前时间戳,然后我可以在多个地方使用它。

我的陈述看起来像这样:

CREATE TRIGGER test7_INSERT AFTER INSERT ON test7 
BEGIN
    WITH t(t) AS (
        SELECT CAST((julianday('now') - 2440587.5)*86400000 
                    AS INTEGER)
    )
    INSERT INTO ChangeLog (t, rowid, field, value)
    VALUES 
    (t.t, 1, 'field1', new.field1),
    (t.t, 1, 'field2', new.field2),
    (t.t, 1, 'field3', new.field3);
END;

但是当我尝试运行此语句时,我在" INSERT"附近出现语法错误。我已重命名其他INSERT以将其隔离到触发器本身内的INSERT语句。一切都在触发器之外工作,当我在TRIGGER上查阅SQLite文档时,我注意到触发器中只允许更新,插入,删除和选择语句 - 显然省略了WITH子句。

如何实现相同的效果,以便我可以在查询的多个位置重复使用相同的时间戳值?

1 个答案:

答案 0 :(得分:2)

我会把它重写为:

INSERT INTO ChangeLog (t, rowid, field, value)
SELECT ":1", ":2", ":3",CAST((julianday('now') - 2440587.5)*86400000  AS INTEGER)
FROM (VALUES
(t.t, 1, 'field1', new.field1),
(t.t, 1, 'field2', new.field1),
(t.t, 1, 'field3', new.field1) ) sub;

<强> DBFiddle Demo

编辑:

WITH cte(c1,c2,c3,c4) AS (
  VALUES  (t.t, 1, 'field1', new.field1),
          (t.t, 1, 'field2', new.field1),
          (t.t, 1, 'field3', new.field1) 
)
INSERT INTO ChangeLog (t, rowid, field, value)
SELECT c1,c2,c3, CAST((julianday('now') - 2440587.5)*86400000  AS INTEGER)
FROM cte;

<强> DBFiddle Demo2

编辑:

INSERT INTO ChangeLog (t, rowid, field, value)
SELECT c1,c2,c3, CAST((julianday('now') - 2440587.5)*86400000  AS INTEGER)
FROM (
    SELECT t.t AS c1, 1 AS c2, 'field1' AS c3, new.field1 AS c4 UNION ALL
    SELECT t.t AS c1, 1 AS c2, 'field2' AS c3, new.field1 AS c4 UNION ALL
    SELECT t.t AS c1, 1 AS c2, 'field3' AS c3, new.field1 AS c4;
) sub