如何使用RECORD在PostgreSQL中返回多行?

时间:2011-08-11 23:59:17

标签: sql postgresql

我正在尝试创建一个在多个表上运行SQL查询并从查询中输出结果表的函数。结果表将有多行。我在这方面遇到了很多困难,而且我已经阅读了建议使用RETURN NEXT的帖子,但我也无法让它工作。根据我的理解RECORD可以使用,因为它采用了输入数据的值。 到目前为止,这是我的代码:

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;

非常感谢任何帮助。感谢。

---------- Word in Progress代码

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;

2 个答案:

答案 0 :(得分:3)

如果我正确理解你的问题,那你试图做这样的事情(对于返回setof的函数我总是使用类型)

CREATE TYPE frt_test_type AS
   (
    country character varying,
    cnt integer,
    country character varying); /* types may vary */

CREATE OR REPLACE FUNCTION
  RETURNS SETOF frt_test_type AS
$BODY$DECLARE r record;
BEGIN
  for r in     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;
  loop
      return next r; 
  end loop;
  return; 
END;$BODY$
  LANGUAGE 'plpgsql'

答案 1 :(得分:0)

根据this answer,你需要的是:

RETURN QUERY SELECT DISTINCT......