access composite array elements plpgsql

走远了吗. 提交于 2019-12-11 07:54:38

问题


I have a array of user-defined composite data type. I need to do some manipulation on the array elements in plpgsql function but I'm not getting the syntax right to access the individual elements. Any help is appreciated. Pasted below is simplified version of the code.

CREATE TYPE playz AS(
                     a integer,
                     b numeric,
                     c integer,
                     d numeric);

CREATE OR REPLACE FUNCTION playx(OUT mod playz[]) AS $$
BEGIN
   FOR i in 1..5 LOOP
       mod[i].a = 1;
       mod[i].b = 12.2;
       mod[i].c = 1;
       mod[i].d = 0.02;

   END LOOP;
END;
$$ LANGUAGE plpgsql;

I get the following error when I try to execute this.

ERROR: syntax error at or near "." LINE 5: mod[i].a = 1;

I'm using Postgres 9.2


回答1:


The left expressions must be pretty simply in PLpgSQL. The combination of array and composite type is not supported. You should to set a value of composite type, and then this value assign to array.

CREATE OR REPLACE FUNCTION playx(OUT mod playz[]) AS $$
DECLARE r playz;
BEGIN
  FOR i in 1..5 LOOP
    r.a = 1;
    r.b = 12.2;
    r.c = 1;
    r.d = 0.02;
    mod[i] = r;
  END LOOP;
END;
$$ LANGUAGE plpgsql;

There is possible a shortcut:

CREATE OR REPLACE FUNCTION public.playx(OUT mod playz[])
LANGUAGE plpgsql
AS $function$
BEGIN
  FOR i in 1..5 LOOP
    mod[i] = ROW(1, 12.2, 1, 0.02);
  END LOOP;
END;
$function$;



回答2:


Following up on Pavel's answer above, you can further simplify this into a plain sql function (which gives you better planner transparency and type checking) if you do something like:

CREATE OR REPLACE FUNCTION playx(OUT mod playz[]) AS $$
select array_agg(row(1, 12.2, 1, 0.02)::playz) 
  from generate_series(1, 5) 
 $$ LANGUAGE sql;

I usually try to use plain SQL functions when I can (pl/pgsql fills a very important niche though).



来源:https://stackoverflow.com/questions/39029020/access-composite-array-elements-plpgsql

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