【问题标题】:What's the easiest way to return a recordset from a PostgreSQL stored procedure?从 PostgreSQL 存储过程返回记录集的最简单方法是什么?
【发布时间】:2011-01-03 09:54:42
【问题描述】:

我只有一个包含国家列表及其 ISO 国家代码的表格。我将查询包装在存储过程(又名函数)中,例如:

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

我得到的错误是:

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

我知道我可以定义一个 TYPE,然后像游标一样遍历记录集,但是 IIRC 在更新版本的 PostgreSQL(我使用的是 8.4.3)下有更好的方法来执行此操作,但我正在拉我的努力回忆。


编辑:

这行得通:

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

注意“RETURNS setof [table name]”。但它似乎不是最灵活的。如果我尝试返回几个表的连接,它就会崩溃。

【问题讨论】:

标签: sql postgresql stored-procedures plpgsql


【解决方案1】:

还有使用RETURNS TABLE(...)的选项(如in the PostgreSQL Manual所述),我个人比较喜欢:

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;

这实际上与使用SETOF tablename 相同,但内联声明表结构而不是引用现有对象,因此连接等仍然有效。

【讨论】:

    【解决方案2】:

    您应该能够使用输出参数,如下所示:

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      • 2013-09-01
      相关资源
      最近更新 更多