2011-01-05 5 views
12

如果在sqlite觸發器中支持/ case/when語句,是否有條件?在sqlite觸發器中的條件插入語句

突然想到說,我有以下設置:

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"

回答

31

這是一個語法錯誤的語法圖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;