Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to return multiple rows in PostgreSQL using RECORD?
    primarykey
    data
    text
    <p>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 <code>RETURN NEXT</code> but I haven't been able to get that to work either. From what I understand <code>RECORD</code> can be used because it takes the values of the data fed into it. Here is my code so far:</p> <pre><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; </code></pre> <p>Any help would be much appreciated. Thanks.</p> <p>---------- Word in Progress code</p> <pre><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; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload