从函数返回查询?
我正在使用 PostgreSQL 8.4,我想创建一个返回包含多行的查询的函数。
以下函数不起作用:
create function get_names(varchar) returns setof record AS $$
declare
tname alias for $1;
res setof record;
begin
select * into res from mytable where name = tname;
return res;
end;
$$ LANGUAGE plpgsql;
record
类型仅允许单行。
如何返回整个查询?我想使用函数作为查询模板。
I am using PostgreSQL 8.4 and I want to create a function that returns a query with many rows.
The following function does not work:
create function get_names(varchar) returns setof record AS $
declare
tname alias for $1;
res setof record;
begin
select * into res from mytable where name = tname;
return res;
end;
$ LANGUAGE plpgsql;
The type record
only allows single row.
How to return an entire query? I want to use functions as query templates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
像这样调用:
要点:
使用
RETURNS TABLE
,因此您不必在每次调用时提供列名称列表。使用
RETURN QUERY
,更简单。对表限定列名,以避免与同名
OUT
参数(包括使用RETURNS TABLE
声明的列)发生命名冲突。使用命名变量而不是
ALIAS
。更简单,做同样的事情,这是首选方法。像这样的简单函数也可以用
LANGUAGE sql
编写:Call like this:
Major points:
Use
RETURNS TABLE
, so you don't have to provide a list of column names with every call.Use
RETURN QUERY
, much simpler.Table-qualify column names to avoid naming conflicts with identically named
OUT
parameters (including columns declared withRETURNS TABLE
).Use a named variable instead of
ALIAS
. Simpler, doing the same, and it's the preferred way.A simple function like this could also be written in
LANGUAGE sql
: