关于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”进行了同样的实验——

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

对视图操作也一样如此:


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



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


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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值