2013-05-09 47 views
0

我使用EXECUTE(动态SQL)和SETOF(结果返回的列表),但它是错误的:(Postgres的动态SQL和列表结果

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'); 
+0

错误:返回“记录”的函数需要列定义列表 第1行:select * from test2('select * from test'); ^ ********** **********错误 错误:需要一个字段定义列表返回 “记录” SQL国家职能:42601 字符:15 – Virus 2013-05-09 01:24:11

回答

1

你必须事先知道返回的记录

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

或者,如果返回的集将永远是一组测试表中,然后使用阿卡什的提出的解决方案的结构。

0

您需要添加一些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; 
$$; 
1

更换

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)