CREATE OR REPLACE FUNCTION clustering_nodes()
RETURNS integer[] AS
$func$
DECLARE
my_var text := '{1,2,3,4,5,6,7,8,9},{1,2,3,4,5},{1,2,3},{8}';
my_array integer[];
arr_len integer[];
BEGIN
FOR my_array IN
SELECT string_to_array(regexp_split_to_table(
trim(my_var, '{}'), '},{'), ',')::int[]
LOOP
arr_len := array_append(arr_len, array_upper(my_array, 1));
END LOOP;
RETURN arr_len;
END
$func$ LANGUAGE plpgsql;
Major points
array_length()
doesn't work on records, only on array.
What's more, there is noarray_length()
in Postgres 8.3. The manual is instrumental in figuring that out yourself. Using the less favorablearray_upper()
instead.Assignment operator in plpgsql is
:=
. Use of=
is undocumented.plpgsql
is an identifier inLANGUAGE plpgsql
, not a string. Do not quote it. May lead to sneaky errors.You can assign variables at declaration time.
STRICT
modifier is pointless without parameters.
-> SQLfiddle demo for Postgres 8.3.
Simpler with modern Postgres
Again, this could be had in a single (if somewhat complex) call:
SELECT array_agg(array_length(string_to_array(txt, ','), 1))
FROM unnest(string_to_array(
trim('{1,2,3,4,5,6,7,8,9},{1,2,3,4,5},{1,2,3},{8}', '{}')
, '},{')
) AS sub(txt);
You need to upgrade to a current version.