关于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。


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





相关文章

项目需要,有个数据需要导入,拿到手一开始以为是mysql,结果...
本文小编为大家详细介绍“怎么查看PostgreSQL数据库中所有表...
错误现象问题原因这是在远程连接时pg_hba.conf文件没有配置正...
因本地资源有限,在公共测试环境搭建了PGsql环境,从数据库本...
wamp 环境 这个提示就是说你的版本低于10了。 先打印ph...
psycopg2.OperationalError: SSL SYSCALL error: EOF detect...