1

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.

2 Answers 2

2
SELECT f0.*, f1.*
FROM
    foo(0) AS f0 (a int, b int),
    foo(1) AS f1 (c int, d int);
Sign up to request clarification or add additional context in comments.

Comments

0

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)
 RETURNS TABLE (a int, b 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.