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

前端 未结 6 1364
生来不讨喜
生来不讨喜 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:32

    If you have a table with this exact record layout, use its name as a type, otherwise you will have to declare the type explicitly:

    CREATE OR REPLACE FUNCTION get_object_fields
            (
            name text
            )
    RETURNS mytable
    AS
    $$
            DECLARE f1 INT;
            DECLARE f2 INT;
            …
            DECLARE f8 INT;
            DECLARE retval mytable;
            BEGIN
            -- fetch fields f1, f2 and f3 from table t1
            -- fetch fields f4, f5 from table t2
            -- fetch fields f6, f7 and f8 from table t3
                    retval := (f1, f2, …, f8);
                    RETURN retval;
            END
    $$ language plpgsql; 
    

提交回复
热议问题