Re: how to get the primary key of a freshly inserted row

From: Darren Ferguson <darren(at)crystalballinc(dot)com>
To: Stuart robinson <stuart(at)zapata(dot)org>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: how to get the primary key of a freshly inserted row
Date: 2002-08-06 19:04:32
Message-ID: Pine.LNX.4.44.0208061502290.28899-100000@thread.crystalballinc.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

CREATE FUNCTION foo(VARCHAR,VARCHAR) RETURNS INTEGER AS '
DECLARE
p1 ALIAS FOR $1;
p2 ALIAS FOR $2;
BEGIN
INSERT INTO foo (a,b) VALUES (p1,p2);
RETURN CURRVAL('id_seq');
END;' LANGUAGE 'plpgsql';

If you use a sequence which it appears you do then just replace id_seq
with the id of your sequence

HTH

On 4 Aug 2002, Stuart robinson wrote:

> I'm writing a PL/pgSQL function that will insert a row and return its
> id. Right now I just do a select after the insert to get the id of the
> new row (see example code below). But I'm guessing that there's a
> better way. Any recommendations?
>
> CREATE FUNCTION foo(VARCHAR, VARCHAR)
> RETURNS INTEGER
> AS '
> DECLARE
> p1 ALIAS FOR $1;
> p2 ALIAS FOR $2;
> v_id INTEGER;
> BEGIN
> INSERT INTO foo (a, b) VALUES (p1, p2);
> SELECT id
> INTO v_id
> FROM foo
> WHERE a = p1 AND
> b = p2;
> RETURN v_id;
> END;
> '
> LANGUAGE 'plpgsql';
>
> Thanks in advance.
>
> --
> Stuart Robinson [stuart(at)zapata(dot)org]
>
> ---------------------------(end of broadcast)---------------------------
> TIP 5: Have you checked our extensive FAQ?
>
> http://www.postgresql.org/users-lounge/docs/faq.html
>

--
Darren Ferguson

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Richard Huxton 2002-08-06 19:07:02 Re: Cannot use more than 16 attributes in an index
Previous Message Ralph Graulich 2002-08-06 19:04:11 Re: View the contents of a database