在这个postgressql函数中,我通过拆分字符串创建了一个数组。现在我想在这个数组上循环并对它进行一些处理。
功能:
CREATE OR REPLACE FUNCTION getAllFoo() RETURNS character varying as
$BODY$
DECLARE
arr_split_data text[];
counter character varying;
begin
counter := ''; -- Init value
-- split data. Add in array
select into arr_split_data regexp_split_to_array('a,b,c,d,e,f',',');
FOR r IN arr_split_data -- error
LOOP
counter := arr_split_data[r] || '_' || counter; -- do some processing
END LOOP;
return counter;
END
$BODY$
LANGUAGE 'plpgsql';
但我收到此错误
当我执行此功能时。我的循环语法是错误的吗?
答案 0 :(得分:4)
语法是
FOREACH r IN ARRAY arr_split_data
LOOP
counter := r || '_' || counter;
-- do some processing
END LOOP;
您还需要声明r
:
DECLARE
arr_split_data TEXT [];
r CHARACTER VARYING;
counter CHARACTER VARYING;
BEGIN
参见手册第41.6.5节:Looping Through Arrays
答案 1 :(得分:0)
CREATE OR REPLACE FUNCTION getAllFoo() RETURNS character varying as
$BODY$
DECLARE
r character varying;
arr_split_data text[];
counter character varying;
begin
counter := ''; -- Init value
-- split data. Add in array
select into arr_split_data regexp_split_to_array('a,b,c,d,e,f',',');
FOREACH r IN array arr_split_data LOOP
counter := counter || '_' || r; -- do some processing
END LOOP;
return counter;
END
$BODY$
LANGUAGE 'plpgsql';