Freitag, 11. Dezember 2009

Creating a history table using SQL triggers

Just for the record and for posterity, this is how to insert a row into table B after a row has been inserted in table a (e.g. something like a foreign key) using a sqlite3 trigger (the trigger would probably work on other databases as well). Add this to a file - call the file "trigger.txt" or something like that:

CREATE TRIGGER mytrigger AFTER INSERT ON table_a
    BEGIN
        INSERT INTO table_b VALUES(NULL,new.primary_id)
END;

Easy, non? Now you have to import the trigger into the sqlite database. Assuming you have already got a database called mydb.db, use this command:
sqlite3 mydb.db < trigger.txt



Now, when you enter a row into table a, a row should automagically be appended to table b.

Keine Kommentare: