更新前触发时的异常选项

时间:2019-05-24 10:41:18

标签: sqlite

我想在sqlite中创建两个触发器。一种是停止更新的触发器,另一种是更改插入日期的触发器。我的问题是,在不激活第一个触发器的情况下,我找不到解决方案来更新插入的值。在sqlite中是否有一个选项可以禁用触发器,或者说不允许更新,而无需在一个列上进行更新?

create trigger if not exists update_buchung before update on Buchung <br>
 begin <br>
  select RAISE(FAIL, "UPDATE NOT ALLOWED"); <br>
 end;<br>

 CREATE TRIGGER if not exists insert_buchung AFTER INSERT  ON Buchung <br>
 BEGIN <br>
  update Buchung SET Datum = datetime('now') WHERE ID = NEW.ID; <br>
 END;<br>

1 个答案:

答案 0 :(得分:0)

我相信您可以取消 insert_buchung 触发器,而可以使用以下任一方法来定义列:-

......., Datum TEXT DEFAULT CURRENT_TIMESTAMP 

......., Datime TEXT DEFAULT (datetime('now'))

考虑:-

DROP TABLE IF EXISTS buchung;
CREATE TABLE buchung (othercolumn TEXT, Datum TEXT DEFAULT (datetime('now')), otherDtaum TEXT DEFAULT CURRENT_TIMESTAMP);
INSERT INTO buchung (othercolumn) VALUES('x'),('y'),('z');
SELECT * FROM buchung;

这同时表明了以下结果:-

enter image description here

即当前日期时间是在插入行时设置的。

但是 insert_buchung 触发器可能是( WHEN子句仅假定一个条件):-

CREATE TRIGGER IF NOT EXISTS update_buchung BEFORE UPDATE ON Buchung
WHEN old.Datum IS NOT NULL -- <<<<<<<<<<<< ADDED
BEGIN
    SELECT RAISE(FAIL, "UPDATE NOT ALLOWED");
END;

例如:-

DROP TABLE IF EXISTS buchung;
DROP TRIGGER IF EXISTS update_buchung;
DROP TRIGGER IF EXISTS insert_buchung;
-- CREATE TABLE buchung (othercolumn TEXT, Datum TEXT DEFAULT (datetime('now')), otherDtaum TEXT DEFAULT CURRENT_TIMESTAMP);
CREATE TABLE IF NOT EXISTS buchung (ID INTEGER PRIMARY KEY,othercolumn TEXT, Datum TEXT);
CREATE TRIGGER IF NOT EXISTS update_buchung BEFORE UPDATE ON Buchung
    WHEN old.Datum IS NOT NULL
    BEGIN
        SELECT RAISE(FAIL, "UPDATE NOT ALLOWED");
    END;
CREATE TRIGGER IF NOT EXISTS insert_buchung AFTER INSERT ON Buchung 
    BEGIN 
        update Buchung SET Datum = datetime('now') WHERE ID = NEW.ID; 
    END;

INSERT INTO buchung (othercolumn) VALUES('x'),('y'),('z');
SELECT * FROM buchung;

结果:-

enter image description here