Re: update trigger not working

From: Oliver Elphick <olly(at)lfix(dot)co(dot)uk>
To: CSN <cool_screen_name90001(at)yahoo(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: update trigger not working
Date: 2005-10-20 02:52:33
Message-ID: 1129776753.19925.49.camel@linda.lfix.co.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, 2005-10-19 at 19:26 -0700, CSN wrote:
> I'm trying to set up a trigger that simply updates a
> field's corresponding timestamp to now() whenever the
> field is updated. But it's not working. Trying to
> debug, I commented out the inner IF and END and the
> log seemed to indicate infinite recursion occurred.

Yes. On update, you are updating again...for ever. What you need to do
is to modify the NEW record in a BEFORE trigger.

> CREATE or REPLACE function update_ts() returns trigger
> as $end$
>
> BEGIN
>
> IF (TG_OP='UPDATE') THEN
>
> IF (OLD.stuff != NEW.stuff) THEN
> UPDATE table1
> set stuff_ts=now()
> where id=NEW.id;

Instead of this, just do:

NEW.stuff_ts = now();

> END IF;
>
> END IF;
>
> RETURN NULL;

RETURN NEW;

>
> END;
>
> $end$ language plpgsql;
>
> CREATE TRIGGER update_ts AFTER UPDATE ON table1 FOR

and make this a BEFORE trigger

> EACH ROW EXECUTE PROCEDURE update_ts();

--
Oliver Elphick olly(at)lfix(dot)co(dot)uk
Isle of Wight http://www.lfix.co.uk/oliver
GPG: 1024D/A54310EA 92C8 39E7 280E 3631 3F0E 1EC0 5664 7A2F A543 10EA
========================================
Do you want to know God? http://www.lfix.co.uk/knowing_god.html

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Douglas McNaught 2005-10-20 02:53:18 Re: update trigger not working
Previous Message Mike Nolan 2005-10-20 02:50:43 Re: update trigger not working