返回行的简单 PostgreSQL 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14178470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple PostgreSQL function to return rows
提问by rebnoob
How do I convert a simple select query like select * from customers
into a stored procedure / function in pg?
如何将简单的选择查询(如select * from customers
pg)转换为存储过程/函数?
I'm new to Postgres and create function customers() as returns table/setof
just didn't feel right and thus the question here.
我是 Postgres 的新手,create function customers() as returns table/setof
只是感觉不对,因此这里的问题。
I understand procs are called "functions" in pg land. Thus does not exist and my only options are to either create a view or a function. The issue is create procedure
create function x() returns setof y
returns a paren'd comma separated row of values which can't be used without further processing (at least that's what I'm seeing in pgAdmin and Ruby/Sequel).
我知道 procs 在 pg land 中被称为“函数”。因此不存在,我唯一的选择是创建视图或函数。问题是create procedure
create function x() returns setof y
返回一个括号逗号分隔的值行,如果不进一步处理就不能使用(至少这是我在 pgAdmin 和 Ruby/Sequel 中看到的)。
create function x() returns table(...)
requires I embed the row definition which I don't want to.
create function x() returns table(...)
要求我嵌入我不想嵌入的行定义。
I'm sure there's a reason behind all this but I'm surprised that the most common use case is this tricky.
我确信这一切背后是有原因的,但令我惊讶的是,最常见的用例是如此棘手。
回答by Erwin Brandstetter
The issue is "create function x() returns setof y" returns a paren'd comma separated row values which can't be used without further processing
问题是“创建函数 x() 返回 setof y”返回一个括号逗号分隔的行值,如果不进一步处理就不能使用
Since the function returns a record / row type, you have to call it with
由于该函数返回记录/行类型,因此您必须使用
SELECT * FROM getcustomers();
to decompose the returned row into individual columns.
将返回的行分解为单独的列。
The manual on CREATE FUNCTIONshould be a good starting point. The example section covers this topic.
该手册上创建功能应该是一个很好的起点。示例部分涵盖了这个主题。
回答by Craig Ringer
Untested but should be about right:
未经测试,但应该是正确的:
CREATE OR REPLACE FUNCTION getcustomers() RETURNS SETOF customers AS $$
SELECT * FROM customers;
$$ LANGUAGE sql;