Re: currval() within one statement

From: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: currval() within one statement
Date: 2008-01-22 07:36:37
Message-ID: 20080122073637.GB21676@a-kretschmer.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

am Tue, dem 22.01.2008, um 10:16:30 +0300 mailte silly_sad folgendes:
> Helo
>
> is it expected that the currval() changes its value between calls within
> one statement ?
>
> Look the following call:
>
> INSERT INTO ttt (a,b) SELECT currval('ttt_id_seq'), 'const' FROM ttt2;

This fails if you never call nextval() for this sequence within this
session.

>
> Where the trigger before insert on ttt is defined and this trigger calls
> nextval('ttt_id_seq').

You don't need a TRIGGER. Just define your table with (a serial, ...)
and omit the column a if you INSERT a new row.

> I was surprised having different values of currval() in ttt.a

If you call nextval() befor the insert, then returns the currval(), for
instance, 5. If you call your insert with the TRIGGER like above, the
currval() returns this value 5, but your trigger fires and increase the
value. And, maybe, an other process has increased the sequence also.

Conclusion, don't call nextval() within a TRIGGER, and insert either
nextval() for the column or omit this column.

Andreas
--
Andreas Kretschmer
Kontakt: Heynitz: 035242/47150, D1: 0160/7141639 (mehr: -> Header)
GnuPG-ID: 0x3FFF606C, privat 0x7F4584DA http://wwwkeys.de.pgp.net

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message sad 2008-01-22 07:54:58 Re: currval() within one statement
Previous Message silly_sad 2008-01-22 07:16:30 currval() within one statement