Re: shorter way to get new value of serial?

From: David Roussel <pgsql-general(at)diroussel(dot)xsmail(dot)com>
To: Harald Armin Massa <haraldarminmassa(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: shorter way to get new value of serial?
Date: 2005-11-19 15:36:59
Message-ID: AC265597-5C53-4349-BEE2-DFC5F429D407@diroussel.xsmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

You can allocate you're numbers from a sequence...
http://www.postgresql.org/docs/7.4/interactive/functions-sequence.html

Then you can peek at the sequence to see what was last allocated.

Exactly how you do it depends on your circumstances.

On 18 Nov 2005, at 13:26, Harald Armin Massa wrote:

> I have a table:
>
>
> CREATE TABLE rechner
> (
> id_r int4 NOT NULL DEFAULT nextval('rechner_id_r_seq'::regclass),
> name text,
> CONSTRAINT rechner_pkey PRIMARY KEY (id_r)
> )
> CREATE UNIQUE INDEX rechner_name
> ON rechner
> USING btree
> (name);
>
> and want to have the existing or new id of 'newobjekt'
>
>
> CREATE OR REPLACE FUNCTION getrechnerid( text)
> RETURNS int4 AS
> ' DECLARE
> result int4;
> BEGIN
> select id_r from rechner where name=upper($1) into result;
>
> IF not FOUND THEN
> select nextval(''swcheck_id_check_seq'') into result;
> insert into rechner (id_r, name) values (result, upper($1));
> END IF;
> return result;
> END;
> '
> LANGUAGE 'plpgsql' VOLATILE;
>
> #############
>
> so on an empty table:
>
> select getrechnerid('LEBERWURST');
> -> 1
>
> select getrechnerid('FISCH');
> -> 2
>
> select getrechnerid('LEBERWURST');
> -> 1
>
> everything is fine. BUT: I feel that this a SO USUAL request
> (please, give me the new primary key of that just inserted beast),
> that there may be a simpler way, and I am just to blind to see.
>
> Is there really one?
>
> Harald
>
> --
> GHUM Harald Massa
> persuasion python postgresql
> Harald Armin Massa
> Reinsburgstraße 202b
> 70197 Stuttgart
> 0173/9409607

In response to

Browse pgsql-general by date

  From Date Subject
Next Message David Roussel 2005-11-19 15:43:56 Re: Anomalies with the now() function
Previous Message Csaba Nagy 2005-11-19 13:14:40 Re: How to debug a locked backend ?