Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional insert statement in sqlite triggers

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"

like image 351
Alex Pacurar Avatar asked Jan 05 '11 20:01

Alex Pacurar


People also ask

Does SQLite support triggers?

At this time SQLite supports only FOR EACH ROW triggers, not FOR EACH STATEMENT triggers. Hence explicitly specifying FOR EACH ROW is optional.

How many types of triggers are there in SQLite?

Action for the trigger, it is the sql statement. There is two SQLite extension to triggers 'OLD' and 'NEW'.

Which of the following is not used as a function rather it is used as a parameter for functions?

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.


2 Answers

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;
like image 175
schlenk Avatar answered Sep 18 '22 01:09

schlenk


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
like image 39
Jefter Junio Avatar answered Sep 19 '22 01:09

Jefter Junio