sqlite触发器是否支持条件if / case / when语句?
假设我有以下设置:
CREATE TABLE someTable (id INTEGER PRIMARY KEY, someValue INTEGER);
CREATE TRIGGER update_another_table AFTER INSERT ON someTable
BEGIN
IF(new.someValue==0)
DELETE FROM another_table WHERE (...some condition);
ELSE
IF NOT EXISTS(SELECT anotherValue FROM another_table WHERE anotherValue =new.someValue)
INSERT INTO another_table VALUES(new.someValue, ...);
ELSE
UPDATE another_table SET anotherValue = new.someValue;
END;
但它会出现语法错误Sqlite error near 'IF': syntax error"
答案 0 :(得分:36)
这是一个语法错误,因为SQLite触发器的语法图不允许任何IF子句或CASE WHEN结构。
但是你可以通过定义两个或三个使用WHEN条件的触发器来达到同样的效果,参见http://sqlite.org/lang_createtrigger.html
所以你会为你的DELETE案例创建触发器,如下所示:
CREATE TRIGGER delete_from_other_table AFTER INSERT ON someTable
WHEN new.someValue = 0
BEGIN
DELETE FROM anotherTable WHERE (... some condition );
END;
然后使用适当的条件为INSERT和UPDATE Case添加另一个触发器......
CREATE TRIGGER update_another_table AFTER INSERT ON someTable
WHEN new.someValue <> 0
BEGIN
...
END;
答案 1 :(得分:0)
以下是带有subselect的触发器的示例:
表格
CREATE TABLE A( ID INTEGER PRIMARY KEY, NAME TEXT ) CREATE TABLE LOG( ID INTEGER PRIMARY KEY, DT TEXT )
使用子选择
CREATE TRIGGER new_lns_historic AFTER INSERT ON A WHEN NEW.ID NOT IN (SELECT ID FROM LOG) BEGIN INSERT INTO LOG VALUES (NEW.ID, DATETIME('NOW')); END