简体   繁体   中英

PostgreSQL: Call a Function More Than Once in FROM Clause

How can I call a function which returns records more than once in FROM clause? I understand that I have to specify a 'column definition list' when using a function that returns records. But how can I then use aliases for that function?

Example:

CREATE OR REPLACE FUNCTION foo(which_foo int) RETURNS SETOF RECORD AS
$BODY$BEGIN
IF which_foo=0 THEN
 RETURN QUERY EXECUTE 'SELECT 1::int,2::int;';
ELSE 
 RETURN QUERY EXECUTE 'SELECT 1::int,2::int;';
END IF;
END$BODY$
LANGUAGE plpgsql;

SELECT * FROM foo(0) AS (a int, b int);;
SELECT * FROM foo(1) AS (c int, d int);
SELECT * FROM foo(0) AS (a int, b int), foo(1) AS (c int, d int);

The last select statement will fail with:

ERROR:  table name "foo" specified more than once

I want to keep using the column definition list, because the function I want to use in the end has to be as generic as possible.

SELECT f0.*, f1.*
FROM
    foo(0) AS f0 (a int, b int),
    foo(1) AS f1 (c int, d int);

I understand that I have to specify a 'column definition list' when using a function that returns records.

No, you do not. I wouldn't operate with anonymous records. Declare the return type , since you already know it:

CREATE OR REPLACE FUNCTION foo(which_foo int)
  AS
$func$
BEGIN
    IF which_foo = 0 THEN
        RETURN QUERY SELECT 1,2;
    ELSE 
        RETURN QUERY SELECT 1,2;
    END IF;
END
$func$ LANGUAGE plpgsql;

And assuming you do not want to combine multiple calls into one row, you should use UNION ALL :

SELECT * FROM foo(0)
UNION ALL
SELECT * FROM foo(1);

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