shorter way to get new value of serial? - Mailing list pgsql-general

From Harald Armin Massa
Subject shorter way to get new value of serial?
Date
Msg-id 7be3f35d0511180526t69bdd767m@mail.gmail.com
Whole thread Raw
Responses Re: shorter way to get new value of serial?  (Jaime Casanova <systemguards@gmail.com>)
Re: shorter way to get new value of serial?  (Andrew Sullivan <ajs@crankycanuck.ca>)
Re: shorter way to get new value of serial?  (David Roussel <pgsql-general@diroussel.xsmail.com>)
Re: shorter way to get new value of serial?  (Alban Hertroys <alban@magproductions.nl>)
List pgsql-general
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

pgsql-general by date:

Previous
From: Byrne Kevin-kbyrne01
Date:
Subject: Anomalies with the now() function
Next
From: Tom Lane
Date:
Subject: Re: How to debug a locked backend ?