I'm trying to create a function which runs an SQL query on multiple tables and outputs the resulting table from the query. The resulting table will have multiple rows. I'm having a lot of difficulty with this and I've read posts which suggest using RETURN NEXT but I haven't been able to get that to work either. From what I understand RECORD can be used because it takes the values of the data fed into it.
Here is my code so far:
CREATE OR REPLACE FUNCTION
most_docs()
RETURNS
SETOF RECORD
AS $$
DECLARE
result RECORD;
BEGIN
CREATE VIEW MOSTDOC AS
SELECT P.country, COUNT(P.country) AS cnt
FROM Producer P, Movie M, ProducerMovie PM
WHERE M.title = PM.title
AND M.year = PM.year
AND P.name = PM.name
AND M.genre = 'Documentary'
GROUP BY P.country;
SELECT DISTINCT M.country INTO result
FROM MOSTDOC M
WHERE M.cnt = (SELECT MAX(M.cnt)
FROM MOSTDOC M);
RETURN result;
END;
$$ LANGUAGE plpgsql;
Any help would be much appreciated. Thanks.
---------- Word in Progress code
CREATE OR REPLACE FUNCTION
most_docs()
RETURNS
SETOF RECORD
AS $$
DECLARE
result RECORD
BEGIN
CREATE VIEW MOSTDOC AS
SELECT P.country, COUNT(P.country) AS cnt
FROM Producer P, Movie M, ProducerMovie PM
WHERE M.title = PM.title
AND M.year = PM.year
AND P.name = PM.name
AND M.genre = 'Documentary'
GROUP BY P.country;
RETURN QUERY SELECT DISTINCT M.country
FROM MOSTDOC M
WHERE M.cnt = (SELECT MAX(M.cnt)
FROM MOSTDOC M);
END;
$$ LANGUAGE plpgsql;