How to declare an array of rowtype in a PostgreSQL function?

不打扰是莪最后的温柔 提交于 2020-08-23 03:54:17

问题


I am trying to create a PostgreSQL function where I will loop over the rows of a query and store some of them in an array, before doing more stuff with it. How can I create an array of rowtype?

CREATE OR REPLACE FUNCTION forExample() RETURNS integer AS
$BODY$
DECLARE
    r "WEBHOST"%rowtype;
    b "WEBHOST"%rowtype[];   <- This does not work !!!
BEGIN
    FOR r IN SELECT * FROM "WEBHOST"
    LOOP
        array_append(b, r);
    END LOOP;
    RETURN 33;
END
$BODY$
LANGUAGE 'plpgsql';

The above function will be more complex, but I am providing a simplified version for this question.


回答1:


CREATE OR REPLACE FUNCTION for_example()
  RETURNS integer AS
$func$
DECLARE
   r "WEBHOST";
   b "WEBHOST"[];         -- this works
BEGIN
   FOR r IN 
      SELECT * FROM "WEBHOST"
   LOOP
      b := b || r;        -- this, too
   END LOOP;

   RAISE NOTICE '%', b;   -- get feedback
   RETURN 33;
END
$func$  LANGUAGE plpgsql; -- and lose the quotes

%rowtype is generally not necessary. Normally, the associated rowtype of a table is available as type of the same name.

And do not quote the language name.

And you cannot just have stand-alone function calls in plpgsql. Using an assignment instead.

It's also not a good idea to use CaMeL-case identifiers in Postgres. Use legal, lower-case identifiers to make your life easier.

The best for last: This can be much simpler with the aggregate function array_agg():

CREATE OR REPLACE FUNCTION for_example()
  RETURNS integer AS
$func$
DECLARE
   b "WEBHOST"[];
BEGIN
   SELECT array_agg(tbl) INTO b FROM "WEBHOST" tbl;       

   RAISE NOTICE '%', b;
   RETURN 33;
END
$func$  LANGUAGE plpgsql;


来源:https://stackoverflow.com/questions/22306765/how-to-declare-an-array-of-rowtype-in-a-postgresql-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!