What's the easiest way to return a recordset from a PostgreSQL stored procedure?

后端 未结 2 1519
抹茶落季
抹茶落季 2021-02-02 02:10

I simply have a table that contains a list of countries and their ISO country codes. I\'m wrapping the query in a stored procedure (aka function) such as:

CREAT         


        
相关标签:
2条回答
  • 2021-02-02 03:10

    There is also the option of using RETURNS TABLE(...) (as described in the PostgreSQL Manual), which I personally prefer:

    CREATE OR REPLACE FUNCTION get_countries()
    RETURNS TABLE(
        country_code text,
        country_name text
    )
    AS $$
        SELECT country_code, country_name FROM country_codes
    $$ LANGUAGE sql;
    

    This is effectively the same as using SETOF tablename, but declares the table structure inline instead of referencing an existing object, so joins and such will still work.

    0 讨论(0)
  • 2021-02-02 03:14

    You should be able to use output parameters, like this:

    CREATE OR REPLACE FUNCTION get_countries(country_code OUT text, country_name OUT text)
    RETURNS setof record
    AS $$ SELECT country_code, country_name FROM country_codes $$
    LANGUAGE sql;
    
    0 讨论(0)
提交回复
热议问题