Re: simple auto-updating timestamp ?

Поиск
Список
Период
Сортировка
От D. Dante Lorenso
Тема Re: simple auto-updating timestamp ?
Дата
Msg-id 3FEF8920.1070003@lorenso.com
обсуждение исходный текст
Ответ на simple auto-updating timestamp ?  (Andreas <maps.on@gmx.net>)
Ответы Re: simple auto-updating timestamp ?
Список pgsql-general
Andreas wrote:

> I suspect, this is a common issue for newbies.
> Is there a simple way to have an auto-updating timestamp like mysql has ?
>
> create table something (
>   id                int4,
>   sometext     text,
>   update_ts    timestamp(0),
>   primary key (id)
> );
>
> Everytime this table gets updated the timestamp should be
> automatically refreshed to NOW() ?
> I hope someone could point me to an example.

You can do this by adding a trigger to your table.  Just define the trigger
to be invoked on INSERT and UPDATE for your table.  The trigger definition
would look something like this:

    CREATE TRIGGER "trg_set_update_ts" BEFORE INSERT OR UPDATE
    ON "public.something" FOR EACH ROW
    EXECUTE PROCEDURE "public"."set_update_ts"();

Then, your function in PL/PGSQL that sets the update_ts to NOW() would look
something like this:

    CREATE FUNCTION "public"."set_update_ts" () RETURNS trigger AS'
    BEGIN
        NEW.update_ts = NOW();
        RETURN NEW;
    END;
    'LANGUAGE 'plpgsql' IMMUTABLE CALLED ON NULL INPUT SECURITY INVOKER;

Of course, this function would end up setting the update_ts to NOW() every
time you insert or update your table.  And you could never set the value
to anything other than NOW() because your trigger would catch it and set it
back to NOW() again.  If that's not exact, it'll at least point you in
the right direction.

Dante

----------
D. Dante Lorenso
dante@lorenso.com







В списке pgsql-general по дате отправления:

Предыдущее
От: Russ Schneider
Дата:
Сообщение: Re: Change onership of database and all tables? (fwd)
Следующее
От: "Chris Travers"
Дата:
Сообщение: Re: Is my MySQL Gaining ?