Frage

I am trying to create the following trigger but it says:

Error while creating trigger: near "INSERT": syntax error Unable to execute statement.

CREATE TRIGGER trig2
   AFTER 
   UPDATE OF flag
   ON table1
   FOR EACH ROW 
BEGIN
    SELECT CASE flag
    WHEN 1 THEN 
        INSERT OR IGNORE INTO stats VALUES(NEW.id,CURRENT_DATE,0);
    ELSE
        DELETE FROM stats WHERE app_id=NEW.id AND ondate=CURRENT_DATE and runtime=0;
    END;
END;

What I want to do is:

  • when flag=1 in table1:
    insert a new row in stats if the record doesn't already exist for same id and ondate.

  • when flag=0:
    delete record from stats with the following constraint:
    WHERE app_id=NEW.id AND ondate=CURRENT_DATE and runtime=0;

I can't figure out what is wrong near "INSERT" please help me out.

War es hilfreich?

Lösung

That is a syntax error as according to the Syntax Diagram for SQLite Triggers we can't have any IF or CASE clause between BEGIN and END.

So you should create two triggers for different operations like this:

1) For Delete Case

CREATE TRIGGER trig1
   AFTER 
   UPDATE OF flag
   ON table1
   FOR EACH ROW 
   WHEN NEW.flag=0
  BEGIN
     DELETE FROM stats WHERE app_id=NEW.id AND ondate=CURRENT_DATE and runtime=0;
  END;

2) For Insert Case

CREATE TRIGGER trig2
   AFTER 
   UPDATE OF flag
   ON table1
   FOR EACH ROW 
   WHEN NEW.flag=1
 BEGIN     
    INSERT OR IGNORE INTO stats VALUES(NEW.id,CURRENT_DATE,0);  
 END;
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top