1

使用 PostgreSQL 9.2,我定义了一个函数,它接受一个参数并返回一个多列表。我想将该函数应用于 CTE 行中的多个参数。我得到的结果是一列元组,而不是我想要的多列。以机智:

sandbox=# CREATE FUNCTION myfunc(arg int) RETURNS table(col1 int, col2 int) AS
sandbox-# 'SELECT arg+1, arg+2'
sandbox-# LANGUAGE SQL;
CREATE FUNCTION
sandbox=# select * from myfunc(1);
 col1 | col2 
------+------
    2 |    3
(1 row)

sandbox=# WITH rows AS (
sandbox(#   SELECT 1 AS arg UNION SELECT 2 AS arg
sandbox(# )
sandbox-# SELECT * FROM (SELECT myfunc(arg) FROM rows) x;
 myfunc 
--------
 (2,3)
 (3,4)
(2 rows)

在给定 CTE 的情况下,以下两个SELECT子句作为具有单列类型的表彼此评估相同record

SELECT myfunc(arg) FROM rows;
SELECT * FROM (select myfunc(arg) FROM rows) x;

以下三个都失败了(CTE 未显示):

SELECT myfunc(arg).col1 FROM rows;
ERROR:  syntax error at or near "."
LINE 4: SELECT myfunc(arg).col1 FROM rows;
                          ^

SELECT col1 FROM (select myfunc(arg) FROM rows) x;
ERROR:  column "col1" does not exist
LINE 4: SELECT col1 FROM (select myfunc(arg) FROM rows) x;
               ^

SELECT col1 FROM (SELECT * FROM (select myfunc(arg) FROM rows) x) y;
ERROR:  column "col1" does not exist
LINE 4: SELECT col1 FROM (SELECT * FROM (select myfunc(arg) FROM row...
               ^

如何获得一个包含单列元组中的值的多列表?

4

1 回答 1

5

在 myfunc 周围有额外的括号很重要。

select (myfunc(arg)).* from rows;
于 2013-10-02T08:51:16.260 回答