I am trying to create a function that runs an SQL query on multiple tables and displays the resulting table from the query. The resulting table will have several rows. I have a lot of difficulties with this, and I read posts that suggest using it RETURN NEXT, but I could not get this to work. From what I understand, RECORDit can be used because it accepts the values โโof the data supplied to it. Here is my 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;
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 greatly appreciated. Thank.
---------- Code in development
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;
source
share