postgres:如何调用返回表并从查询中传递params的函数

时间:2017-01-27 14:14:42

标签: sql postgresql postgresql-9.5 set-returning-functions lateral

作为一个例子:

返回表的函数:

=> create or replace function testf(x integer)
     returns table(a integer, b integer)
   language sql
   as $function$
       select * from (values(1,2)) as foo(a,b)
   $function$;

调用它以便返回记录(或任何你称之为的记录):

=> select testf(3);
 testf
-------
 (1,2)

调用它以便返回一个表(好):

=> select * from  testf(3);
 a | b
---+---
 1 | 2

但是如何调用它以使参数来自查询?

=> select s.n, testf(s.n) from (select 3 as n union select 4) s;
 n | testf
---+-------
 3 | (1,2)
 4 | (1,2)            <-- not a table (or row with column names)


=> select * from  testf(s.n) from (select 3 as n) s;
 ERROR:  syntax error at or near "from"
 LINE 1: select * from  testf(s.n) from (select 3 as n) s;

1 个答案:

答案 0 :(得分:2)

使用LATERAL子查询:

SELECT *
FROM  (VALUES (3), (4)) AS s(n)
     , testf(s.n);

逗号是CROSS JOIN LATERAL的简短表示法,因为LATERAL自动使用FROM子句中的set-returns函数。

相关: