简体   繁体   中英

plpgSQL return record type from FUNCTION

I'm trying to use a plgSQL witch return me a record type :

CREATE FUNCTION actu(id INTEGER) RETURNS RECORD  AS $$
    DECLARE 
      ret RECORD;
    BEGIN
      SELECT id_photo, id_user, lien, titre 
            FROM photo 
            WHERE id_user IN (
                                SELECT id_userabo 
                                FROM abo 
                                WHERE id_user = id ) 
            ORDER BY date_publi DESC LIMIT 10;

    RETURN ret;
    END;$$
LANGUAGE plpgsql;

When I'm trying to use it with :

SELECT * FROM actu(4)
AS (id_photo Integer, id_photo Integer, lien Varchar, titre Varchar);

pgAdmin4 send me error :

ERROR: ERROR: the request has no destination for the resulting data HINT: If you want to cancel the results of a SELECT, use PERFORM instead. CONTEXT: PL/pgsql function fil_actu(integer), line 5 with SQL statement

You may define those types inside the function, but with different names for the types. The return type can be a TABLE type and use RETURN QUERY to return the results.

CREATE FUNCTION actu(id INTEGER) RETURNS TABLE 
(typ_id_photo Integer, typ_id_user Integer, typ_lien Varchar, typ_titre Varchar) 
AS $$
    BEGIN
  RETURN QUERY   
     SELECT id_photo, id_user, lien, titre 
  FROM photo p 
  WHERE id_user IN (SELECT id_userabo 
                    FROM abo 
                    WHERE id_user = id ) 
  ORDER BY date_publi DESC 
  LIMIT 10;

    END;$$
LANGUAGE plpgsql;

The immediate error is, that the result of a select statement needs to be stored somewhere (that's what the error says). You would need to use select .. into ret from ... to store the result, but that wouldn't work as a variable of type record can only store one row from a result.

You apparently want to return more than just one row, so you need to define the function as returns table() and then use return query in PL/pgSQL to return the result of a query. But for a simple function encapsulating a SELECT query, a language sql function is more efficient.

CREATE FUNCTION actu(id INTEGER) 
  -- adjust the data types for the returned columns!
  RETURNS table (id_photo int, id_user int, lien text, titre text)
AS $$
  SELECT id_photo, id_user, lien, titre 
  FROM photo 
  WHERE id_user IN (SELECT id_userabo 
                    FROM abo 
                    WHERE id_user = id ) 
  ORDER BY date_publi DESC 
  LIMIT 10;
$$
LANGUAGE sql;

You can use that function like this:

select *
from actu(42);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM