Reputation: 21
I currently have two tables:
tblFoo
foo_id foo_text
1 foo
and
tblBar
bar_id foo_id bar_text
100 1 hello
101 1 world
I am trying to return a polymorphic row type using a function, a la:
CREATE OR REPLACE FUNCTION fetch_foo(p_foo_id int) RETURNS record as $$
DECLARE
rec record;
BEGIN
SELECT
F.foo_id,
foo_text,
array_agg(bar_text) as bar_text
FROM tblFoo F
LEFT JOIN tblBar B
ON F.foo_id = B.foo_id
WHERE F.foo_id = p_foo_id
GROUP BY F.foo_id
INTO rec;
RETURN rec;
END
$$ LANGUAGE plpgsql;
Currently, this is returning a single concatenated field called 'fetch_foo' of (1,"foo","{hello,world}")
. I have read the reply at Return multiple fields as a record in PostgreSQL with PL/pgSQL and understood that I shouldn't need to create a type here to return a record with separate fields. What am I overlooking?
Thanks.
Upvotes: 0
Views: 357
Reputation:
You don't need to define a record. It's a lot simpler than that, just define it as "returns table" and use SQL not PL/pgSQL.
CREATE OR REPLACE FUNCTION fetch_foo(p_foo_id int)
RETURNS table(foo_id int, foo_text text, bar_text text[])
AS
$$
SELECT
F.foo_id,
foo_text,
array_agg(bar_text) as bar_text
FROM tblFoo F
LEFT JOIN tblBar B
ON F.foo_id = B.foo_id
WHERE F.foo_id = $1
GROUP BY F.foo_id
$$
LANGUAGE sql;
Upvotes: 2