Skip site navigation (1) Skip section navigation (2)

Re: [SQL] SQL stored function inserting and returning data in arow.

From: Hocine Abir <Hocine(dot)Abir(at)iutv(dot)univ-paris13(dot)fr>
To: pgsql-admin(at)postgresql(dot)org
Subject: Re: [SQL] SQL stored function inserting and returning data in arow.
Date: 2008-01-11 11:06:45
Message-ID: 20080111120645.ev3hse9w9lskogwo@mail.iutv.univ-paris13.fr (view raw or flat)
Thread:
Lists: pgsql-adminpgsql-sql
Selon Daniel Caune <daniel(dot)caune(at)ubisoft(dot)com>:

> Hi,
>
> Is there any way to define a SQL stored function that inserts a row in a
> table and returns the serial generated?
>
> CREATE TABLE matchmaking_session
> (
>   session_id bigint NOT NULL DEFAULT
> nextval('seq_matchmaking_session_id'),
>   ...
> );
>
> CREATE FUNCTION create_matchmaking_sesssion(...)
>   RETURNS bigint
> AS $$
>   INSERT INTO matchmaking_session(...)
>     VALUES (...)
>     RETURNING session_id;
> $$ LANGUAGE SQL;
>
> 2008-01-10 22:08:48 EST ERROR:  return type mismatch in function
> declared to return bigint
> 2008-01-10 22:08:48 EST DETAIL:  Function's final statement must be a
> SELECT.
> 2008-01-10 22:08:48 EST CONTEXT:  SQL function
> "create_matchmaking_sesssion"
>
> I can easily convert this code into a PL/pgSQL function, but I'm
> thinking that pure SQL is more natural (and faster?) for such a stored
> function.
>
> Regards,
>
> --
> Daniel
>
> ---------------------------(end of broadcast)---------------------------
> TIP 4: Have you searched our list archives?
>
>                http://archives.postgresql.org
>

  Just add a SELECT query like this :

CREATE FUNCTION create_matchmaking_session()
   RETURNS bigint
AS $$
    INSERT INTO matchmaking_session
     VALUES (nextval('seq_matchmaking_session_id'));

    SELECT currval('seq_matchmaking_session_id') as  session_id;

$$ LANGUAGE SQL;

-- 
Hocine Abir
IUT de Villetaneuse


In response to

pgsql-admin by date

Next:From: Marcin StępnickiDate: 2008-01-11 11:15:00
Subject: Re: SQL stored function inserting and returning data in a row.
Previous:From: Gerardo HerzigDate: 2008-01-11 11:03:07
Subject: Re: SQL stored function inserting and returning data in a row.

pgsql-sql by date

Next:From: Marcin StępnickiDate: 2008-01-11 11:15:00
Subject: Re: SQL stored function inserting and returning data in a row.
Previous:From: Gerardo HerzigDate: 2008-01-11 11:03:07
Subject: Re: SQL stored function inserting and returning data in a row.

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group