2015-01-15 87 views
3

我有一个具有返回记录类型的函数。当返回类型是记录类型时,函数只返回一列postgres

下面是功能正在使用,基本功能做什么的,它需要在输入放慢参数和查询数据库返回的列:

drop function if exists test_proc(sr_number1 bigint); 
create or replace function test_proc(sr_number1 bigint) RETURNS record /*SETOF tbl*/ AS $$ 

declare 
i integer default 0; 
record_type record; 
begin 
select sr_num,product_number,phone,addr into record_type from my_table where sr_num=sr_number1; 
return record_type; 
end 
$$ LANGUAGE plpgsql; 

不幸的是,当我执行的功能

select test_proc(12345);我在(sr_num,product_number,phone,addr)这样的一列中得到了逗号分隔列表的结果。但是我希望能够返回的是一个包含列值和它们各自列名的表格行。

我也试过执行功能

select * from test_proc(12345); but get the following error 

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

'选择* from'是使用返回结果集的功能的正确方法。你可以声明函数为'returns table(...)',那么当你从表中选择时,你不需要指定列名。 – 2015-01-15 15:41:04

+0

@a_horse_with_no_name返回类型应该如何?你能否发布我的代码版本的修改后的功能?我试图返回表,但无法解决问题。 – user2569524 2015-01-15 16:31:02

回答

1

当查询返回的记录的功能,你必须指定要在结果中得到记录的类型

select * from test_proc(12345) f(b bigint, t text); 

这应该工作。

更好的解决方案是申报记录的类型在功能

CREATE OR REPLACE FUNCTION test_proc(sr_number1 bigint) 
RETURNS TABLE(b bigint, t text) AS $$ $$