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"
At this time SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence explicitly specifying FOR EACH ROW is optional.
Action for the trigger, it is the sql statement. There is two SQLite extension to triggers 'OLD' and 'NEW'.
Actually now is not a function. Rather than it is a timestring parameter which is used in various SQLite functions to retrieve the current date and time.
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;
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With