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

醉酒当歌 提交于 2019-12-03 06:18:42

问题


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:

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

The error I am getting is:

ERROR:  a column definition list is required for functions returning "record"

I know that I can define a TYPE and then loop through the recordset like a cursor, but IIRC there's a better way to do this under newer versions of PostgreSQL (I'm using 8.4.3) but I'm pulling my hair out trying to remember.


Edit:

This works:

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

Note the "RETURNS setof [table name]". But it doesn't seem to be the most flexible. It falls apart if I attempt to return a join of several tables.


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/2036093/whats-the-easiest-way-to-return-a-recordset-from-a-postgresql-stored-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!