简体   繁体   中英

How to call a "table function" repeatedly in a single query?

I have written a function in PostgreSQL where I pass a date and it returns a table with few columns.

I want to run that function in a loop for 5 times in a CTE (common table expression).

How to implement that properly?

"Running a function in a loop" is one way to implement something.
Depending on what you actually want , a set-based solution instead of a loop is probably a good implementation in SQL:

WITH cte AS (
   SELECT (my_set_returning_function(d)).*  -- ①
   FROM   unnest('{2022-07-01, 2022-08-02, 2022-09-03}'::date[]) d
   )
-- do something with it
SELECT *
FROM   cte ...

But for internal reasons you better formulate as :

WITH cte AS (
   SELECT (func_result).*  -- ①
   FROM  (
      SELECT my_set_returning_function(d) AS func_result
      FROM   unnest('{2022-07-01, 2022-08-02, 2022-09-03}'::date[]) d
      ) sub
   )
...

See:

Requires Postgres 10 or later:

① About decomposing a row type, see:

This works for any given array of dates.

For a small, fixed number of dates, you might just use UNION ALL :

WITH cte AS (
   SELECT * FROM my_set_returning_function('2022-07-01')
   UNION ALL
   SELECT * FROM my_set_returning_function('2022-08-02')
   UNION ALL
   SELECT * FROM my_set_returning_function('2022-09-03')
   )
...

If you insist on said loop , you have to write another function using a procedural language like PL/pgSQL that actually features loops - unlike SQL.

The closest thing to a loop in SQL would be a recursive CTE, but I seriously doubt that would make sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM