You don't need a loop for that, you could use unnest to convert the array from string_to_array into a set of rows and then use a simple insert ... select construct:
create or replace function ff(int, text) returns integer as $$
begin
insert into test(i, t)
select $1, s
from unnest(string_to_array($2, ',')) as dt(s);
return 0;
end
$$ language plpgsql;
I've also corrected some typos (RETRUNS, RETRUN, and pgsql) along the way.
You could also use regexp_split_to_table:
create or replace function ff(int, text) returns integer as $$
begin
insert into test(i, t)
select $1, s
from regexp_split_to_table($2, ',') as dt(s);
return 0;
end
$$ language plpgsql;
If you're stuck in the 8.1 stone age and can't do anything about it, then perhaps something like this would work:
create or replace function ff(int, text) returns integer as $$
declare
a text[];
i int;
begin
select string_to_array($2, ',') into a;
i := 1;
loop
if i > array_upper(a, 1) then
exit;
else
insert into test(i, t) values($1, a[i]);
i := i + 1;
end if;
end loop;
return 0;
end
$$ language plpgsql;
I think that should work in 8.1 but I don't have access to 8.1 to check.