Re: getting a sequence value

From: Dave Cramer <pg(at)fastcrypt(dot)com>
To: Nico <nicohmail-postgresql(at)yahoo(dot)com>
Cc: pgsql-jdbc(at)postgresql(dot)org
Subject: Re: getting a sequence value
Date: 2005-03-21 12:28:42
Message-ID: 423EBDFA.9040507@fastcrypt.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-jdbc

you can either retrieve the nextval before inserting and insert it or
let the default constraint
insert it for you and retrieve it using currval

1)
select nextval('public."tblTable1_FieldID_seq"'::text)
then insert this value into table 1 and you will know the value beforehand

2)
allow the insert to go through
select currval('public."tblTable1_FieldID_seq"'::text)
and then use this to insert into table 2

FYI currval does the "right" thing. It is guaranteed to be the value
your connection retrieved from the sequence.

Dave

Nico wrote:

>Hi,
>I have two tables where the second table has a foreign key to the first one.
>When I insert a row in the first one, I need the value of the ID generated
>by a sequence in the first table to insert it in the foreign key column in
>the second table. Except I don't know how to do this in Java/PostgreSQL...
>Anyone knows how?
>Table data:
>Table 1:
>Field1 (integer) default: nextval('public."tblTable1_FieldID_seq"'::text)
>other field...
>Table 2:
>Field1 (integer) default: nextval('public."tblTable2_FieldID_seq"':text)
>Field2 (integer) foreign key that references to Field1 in Table 1...
>
>So when I do this:
>INSERT INTO "tblTable1"(other fields...) VALUES(...);
>how do I know what to put in here?
>INSERT INTO "tblTable2"("Field2", other fields...) VALUES(???, ...);
>
>I know in MS SQL server and Oracle one uses an old and new resultset to
>resolve this issue, but haven't a clue how to do this in Java/PostgreSQL...
>
>Nico.
>
>
>
>---------------------------(end of broadcast)---------------------------
>TIP 1: subscribe and unsubscribe commands go to majordomo(at)postgresql(dot)org
>
>
>
>

--
Dave Cramer
http://www.postgresintl.com
519 939 0336
ICQ#14675561

In response to

Responses

Browse pgsql-jdbc by date

  From Date Subject
Next Message Guillaume Cottenceau 2005-03-21 12:37:44 Re: getting a sequence value
Previous Message Nico 2005-03-21 11:28:33 getting a sequence value