微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关于postgresql的returns table调用时的显示问题

首先,查官网上的解释。




35.4.9. SQL Functions Returning TABLE

There is another way to declare a function as returning a set,which is to use the Syntax RETURNS TABLE(columns). This is equivalent to using one or more OUT parameters plus marking the function as returning SetoF record (or SetoF a single output parameter's type,as appropriate). This notation is specified in recent versions of the sql standard,and thus may be more portable than using SetoF.

For example,the preceding sum-and-product example Could also be done this way:

CREATE FUNCTION sum_n_product_with_tab (x int)
RETURNS TABLE(sum int,product int) AS $$
    SELECT $1 + tab.y,$1 * tab.y FROM tab;
$$ LANGUAGE sql;

It is not allowed to use explicit OUT or INOUT parameters with the RETURNS TABLE notation — you must put all the output columns in the TABLE list.




写完function之后,一调用,发现显示如图

完全不是我想要的样子,我想要的是多行多列的。于是去百度使劲查,可是因为RETURNS TABLE是新功能百度搜不到。于是我去google查,在stackoverflow里查到了一个类似的例子。http://stackoverflow.com/questions/18084936/pl-pgsql-functions-how-to-return-table-with-an-execute-statement


里面有一条回答:Are you calling function with SELECT my_function(123); or SELECT FROM my_function(123); ?


太妙了!我回去试了一下,第一次我调用的方式是:SELECT list_last_bill('yhc95@outlook.com');这样返回的是单列模式,就是上图那样。

于是我换成以下调用方式:SELECT * from list_last_bill('yhc95@outlook.com');成功了!!变成多行多列了!

我又试了如下调用方式,去掉*:SELECT from list_last_bill('yhc95@outlook.com');只显示行数


随机又对表格“contract”进行了同样的实验——

在selectfrom的时候,一样,只是返回行数,但是当直接selectcontract时,显示的是字段不存在。

对视图操作也一样如此:


说明RETURNS TABLES胜似表格,却在直接select时比表格多了一个功能——将多列压缩成一列输出



当function返回的是table时,相当于重新创建了一个表格,此时就不能像以前调用function一样简单粗暴地直接使用select+function_name,而是要像调用表格中所有列一样,select*fromfunction_name。


特此铭记,折腾了我一个小时,找不出原因。





版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐