问题
Are conditional if/case/when statements supported in sqlite triggers?
Let`s say I have the following setup:
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;
But it rises a syntax error Sqlite error near 'IF': syntax error"
回答1:
That is an syntax error as the Syntax Diagram for SQLite Triggers does not allow any IF clauses nor CASE WHEN constructions.
But you can achieve the same effect by defining two or three triggers that use the WHEN condition, see http://sqlite.org/lang_createtrigger.html
So you would create on trigger for your DELETE case like this:
CREATE TRIGGER delete_from_other_table AFTER INSERT ON someTable
WHEN new.someValue = 0
BEGIN
DELETE FROM anotherTable WHERE (... some condition );
END;
And than add another trigger for the INSERT and UPDATE Case with the appropriate conditions...
CREATE TRIGGER update_another_table AFTER INSERT ON someTable
WHEN new.someValue <> 0
BEGIN
...
END;
回答2:
Below is an example of a trigger with subselect:
Tables
CREATE TABLE A( ID INTEGER PRIMARY KEY, NAME TEXT ) CREATE TABLE LOG( ID INTEGER PRIMARY KEY, DT TEXT )
Created trigger with sub select
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
来源:https://stackoverflow.com/questions/4608871/conditional-insert-statement-in-sqlite-triggers