Return multiple fields as a record in PostgreSQL with PL/pgSQL

前端 未结 6 1377
生来不讨喜
生来不讨喜 2020-11-27 11:57

I am writing a SP, using PL/pgSQL.
I want to return a record, comprised of fields from several different tables. Could look something like this:

CREATE O         


        
6条回答
  •  生来不讨喜
    2020-11-27 12:37

    You need to define a new type and define your function to return that type.

    CREATE TYPE my_type AS (f1 varchar(10), f2 varchar(10) /* , ... */ );
    
    CREATE OR REPLACE FUNCTION get_object_fields(name text) 
    RETURNS my_type 
    AS 
    $$
    
    DECLARE
      result_record my_type;
    
    BEGIN
      SELECT f1, f2, f3
      INTO result_record.f1, result_record.f2, result_record.f3
      FROM table1
      WHERE pk_col = 42;
    
      SELECT f3 
      INTO result_record.f3
      FROM table2
      WHERE pk_col = 24;
    
      RETURN result_record;
    
    END
    $$ LANGUAGE plpgsql; 
    

    If you want to return more than one record you need to define the function as returns setof my_type


    Update

    Another option is to use RETURNS TABLE() instead of creating a TYPE which was introduced in Postgres 8.4

    CREATE OR REPLACE FUNCTION get_object_fields(name text) 
      RETURNS TABLE (f1 varchar(10), f2 varchar(10) /* , ... */ )
    ...
    

提交回复
热议问题