tags:

views:

37

answers:

1

Hello,

I'm working on setting up a simple SQLite database to access via Python. So far I have one basic table, and a couple of triggers - I want to have one trigger update a field column 'date_added' when a new record is added, and another one to update a column 'date_updated' when a record is later updated. Here is my SQLite syntax for the triggers:

CREATE TRIGGER add_contact AFTER INSERT ON contact_info
BEGIN
UPDATE contact_info SET date_added = DATETIME('NOW') WHERE pkid = new.pkid;
END;

CREATE TRIGGER update_contact AFTER UPDATE ON contact_info
BEGIN
UPDATE contact_info SET date_updated = DATETIME('NOW') WHERE pkid = new.pkid;
END;

The 'add_contact' trigger seems to be working fine... it fires when I add a new record via an sql INSERT command, as planned.

The problem seems to be the 'update_contact' trigger... it fires both when I update a record via an sql UPDATE command (as planned) and when I add a new record also:

i.e. when I add a new record I get this in the 'date_added' and 'date_updated' columns:

2010-07-12 05:00:06|2010-07-12 05:00:06

and when I update that record, it changes like so:

2010-07-12 05:00:06|2010-07-12 05:14:26

I guess I'm not getting why the UPDATE trigger fires on INSERT also?

TIA,

Monte

Edited to add: Any hints on how to make it work as intended?

+1  A: 

You have an UPDATE in your INSERT trigger. So the INSERT causes an UPDATE. Which you have hooked with a different trigger.

Borealid
Whoops! I see what you mean ;)Any idea how to achieve the original goals of two separate triggers, one that fires on an INSERT, and one that fires on UPDATE?Seems like if there was a way to fire the 'update_contact' trigger on the update of any field *except* date_added, that should do it. Just not sure how to go about it...
memilanuk
@memilanuk: You could compare OLD.date_added to NEW.date_added in your UPDATE trigger?
Borealid
Just an update on an old thread, as I got around to tinkering with the code in question again today. I changed the trigger code to read: UPDATE contact_info SET date_updated = DATETIME('NOW') WHERE pkid = new.pkid AND DATETIME('NOW') != date_added; Seems to work. Thanks for the nudge in the right direction!
memilanuk