加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 17:20:33 所属栏目:百科 来源:网络整理
导读:首先,查官网上的解释。 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 ma

首先,查官网上的解释。




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。


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



??

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读