Re: [SQL] Retrieving the new "nextval" for primary keys....

From: Kevin Brannen <kevinb(at)nurseamerica(dot)net>
To: Greg Patnude <GPatnude(at)adelphia(dot)net>
Cc: pgsql-general(at)postgresql(dot)org, pgsql-sql(at)postgresql(dot)org
Subject: Re: [SQL] Retrieving the new "nextval" for primary keys....
Date: 2002-08-28 16:09:27
Message-ID: 3D6CF5B7.90206@nurseamerica.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general pgsql-sql

Greg Patnude wrote:
> I am using postgreSQL with Perl::CGI and Perl::DBI::Pg... I would like to be
> able to insert a row from my Perl script [$SQL->exec();] and have postgreSQL
> return the id of the newly inserted record (new.id) directly to the Perl
> script for further processing... Anyone with a solution / idea ???
>
> Nearly EVERY table I create in postgreSQL (7.2) has the following minimum
> structure:
>
> create table "tblName" (
>
> id int4 primary key nextval ("tblName_id_seq"),
>
> ..field...
> )

You can either do it in 2 statements, something like:

$dbh->do("insert into tblName ...");
my ($id) = $dbh->selectrow_array("select currval('tblName_id_seq')");

Or you could create a function which takes the insert statement, and
ends with doing a select on the currval (as above) and returning that.
As I do the 2 statement approach above, I haven't done a function, but
it doesn't look like it would be that hard to do.

HTH,
Kevin

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Jochem van Dieten 2002-08-28 16:13:26 Re: Data files became huge with no apparent reason
Previous Message scott.marlowe 2002-08-28 16:08:57 Re: Noobie Questions...

Browse pgsql-sql by date

  From Date Subject
Next Message tp 2002-08-28 16:09:29 UPDATE & LIMIT together?
Previous Message Vivek Khera 2002-08-28 15:28:21 Re: LIMIT 1 FOR UPDATE or FOR UPDATE LIMIT 1?