2011-08-15 104 views
15

我目前正在写postgresql 9.04中的一个函数,我试图使用一个将在select语句中使用的变量,然后返回结果。函数返回多个列作为单列而不是多列

我提出的陈述很简单,很有效;但是,所有列都输出到单列而不是多列。

这里是我的功能:

create or replace function foo(IN pID integer, OUT project_id integer, OUT project_name text, OUT project_type text, OUT project_description text, OUT project_status text) 
returns setof record as 

$$ 
select project_id, project_name, project_type, project_description, project_status from  t_projects 
where project_id = $1; 
$$ 

LANGUAGE SQL; 


select foo(6) -- runs function 

电流输出是这样的:

"(6,"test project","inbound","inbound test","processing")" 

我怎样才能使它所以结果并不连接在一起,并seperately返回各列项?

谢谢你提前。

+1

为什么你有一个'setof记录'的返回类型,同时还声明'OUT'列匹配' SELECT'?你打算返回记录,还是填充'OUT'参数?你应该选择一种方法,而不是两种。 – cdhowie

+0

postgresql对我来说仍然是新手,因为我习惯于使用微软sql erver。理想情况下,我想返回select语句的结果。在我的谷歌搜索中,我发现人们会用指定的输出创建一个类型,或者将输出放在函数中。目前,我仍处于postgresql的理解阶段:) – richh

回答

27

你需要调用该函数是这样的:

select * from foo(6); 

将返回这样的事情:

project_id | project_name | project_type | project_description | project_status 
-----------|--------------|--------------|---------------------|---------------- 
     6 | test project |  inbound |  inbound test |  processing 

这是Postgres的,它可以被称为左右逢源的怪癖,给你一个结果。您可能希望再次查看有关设置返回函数的文档,还有其他方法可以执行此操作。哦,这里有一个wiki页面,用于plpgsql,但大多数也适用于sql函数:http://wiki.postgresql.org/wiki/Return_more_than_one_row_of_data_from_PL/pgSQL_functions

+0

这样做了......谢谢SOOOO太多:) – richh

+0

这确实很古怪。 – mvexel

+0

为什么'select * from foo(6)'是用'create或replace函数定义foo()时出错的错误foo(int)返回setof记录为$$ SELECT $ 1为a,'xx'为b; $$ LANGUAGE SQL;'?? –