2015-01-15 89 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 $$ $$