Updating a date field

Started by DCover 23 years ago3 messagesgeneral
Jump to latest
#1DC
danc@bspmail.com

I have a date field called "updated" with a default of now.
When I INSERT data it the field displays today's date.
My problem is when I UPDATE the row it doesn't change unless
I update the field manually like this:
UPDATE person SET email='doe@foo.com',updated='now()' WHERE
person_id=614486;
Is there an automatic way?
I tried doing it with a rule, which returned
ERROR: query rewritten 10 times, may contain cycles
I tried a CONSTRAINT and TRIGGER without any luck either.
Can anyone help?

#2Stephan Szabo
sszabo@megazone23.bigpanda.com
In reply to: DC (#1)
Re: Updating a date field

On Mon, 19 Aug 2002, Dan C wrote:

I have a date field called "updated" with a default of now.
When I INSERT data it the field displays today's date.
My problem is when I UPDATE the row it doesn't change unless
I update the field manually like this:
UPDATE person SET email='doe@foo.com',updated='now()' WHERE
person_id=614486;
Is there an automatic way?
I tried doing it with a rule, which returned
ERROR: query rewritten 10 times, may contain cycles
I tried a CONSTRAINT and TRIGGER without any luck either.

A before trigger should do it for you (untested)

create function setupdated() returns opaque as '
begin
NEW.updated := now();
return NEW;
end;'
language 'plpgsql';

create trigger person_setupdated before update on
person for each row execute procedure setupdated();

#3Jules Alberts
jules.alberts@arbodienst-limburg.nl
In reply to: Stephan Szabo (#2)
Re: Updating a date field

On 19 Aug 2002 at 14:17, Stephan Szabo wrote:

On Mon, 19 Aug 2002, Dan C wrote:

I have a date field called "updated" with a default of now.
When I INSERT data it the field displays today's date.
My problem is when I UPDATE the row it doesn't change unless
I update the field manually like this:
UPDATE person SET email='doe@foo.com',updated='now()' WHERE
person_id=614486;
Is there an automatic way?
I tried doing it with a rule, which returned
ERROR: query rewritten 10 times, may contain cycles
I tried a CONSTRAINT and TRIGGER without any luck either.

A before trigger should do it for you (untested)

create function setupdated() returns opaque as '
begin
NEW.updated := now();
return NEW;
end;'
language 'plpgsql';

create trigger person_setupdated before update on
person for each row execute procedure setupdated();

I do this too (with CURRENT_TIMESTAMP), and also include the last
person who has updated the row (current_user). You can also set these
fields to DEFAULT values and use the trigger to update them when the
row is updated.