【问题标题】:Postgres dynamic sql and list resultPostgres 动态 sql 和列表结果
【发布时间】:2013-05-09 01:21:21
【问题描述】:

我使用了 EXECUTE(用于动态 sql)和 SETOF(结果以列表形式返回),但它是错误的 :(

create table test as
select 1 id, 'safd' data1,'sagd' data2
union
select 2 id, 'hdfg' data1,'sdsf' data2;

create or replace function test2(a varchar) returns SETOF record as
$BODY$
declare x record;
begin
for x in execute a loop
RETURN NEXT x;
end loop;
return;
end;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;

select * from test2('select * from test');

【问题讨论】:

  • 错误:返回“记录”的函数需要列定义列表 LINE 1: select * from test2('select * from test'); ^ ********** 错误 ********** 错误:返回“记录”的函数需要列定义列表 SQL 状态:42601 字符:15

标签: postgresql dynamic record


【解决方案1】:

你必须提前知道返回记录的结构

select * from test2('select * from test') s(a int, b text, c text);
 a |  b   |  c   
---+------+------
 1 | safd | sagd
 2 | hdfg | sdsf

或者,如果返回的集合始终是测试表的集合,则使用 Akash 建议的解决方案。

【讨论】:

    【解决方案2】:

    替换

    create or replace function test2(a varchar) returns SETOF RECORD as
    

    create or replace function test2(a varchar) returns SETOF test as
                                                              ^^^^ name of table (it specifies the datatypes of the set)    
    

    【讨论】:

      【解决方案3】:

      您需要添加一些 OUT 参数。

      CREATE FUNCTION test2(a character varying, OUT id integer, OUT data1 text, OUT data2 text) RETURNS SETOF record
      LANGUAGE plpgsql
      AS $$
      begin
      RETURN QUERY EXECUTE a;
      end;
      $$;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-12
        • 1970-01-01
        • 2023-01-08
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多