问题
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