6

如何在某个分隔符上拆分字符串,然后遍历各个部分?我尝试了一些函数和循环类型,但没有成功。我正在尝试实现以下目标:

create or replace function splitloop() returns void
as $$
DECLARE
part text;
BEGIN
   foreach part in string_to_array('one,two,three', ',')
   loop
      -- do something with part
   end loop;
END;
$$ language plpgsql;
4

2 回答 2

9

您应该在实际数组之前添加单词“数组”:

foreach part in array string_to_array('one,two,three', ',')
loop
    -- do something with part
end loop;

sql fiddle demo

关于遍历数组的文档。

于 2013-09-29T18:10:11.573 回答
3

If you can recast your problems in terms of a set-based operation (plain SQL query), you should do so. unnest() is the key set-returning function. Can also be wrapped in an sql or plpgsql function. plpgsql syntax:

RETURN QUERY
SELECT unnest(string_to_array('one,two,three', ','))
...

Details depend on your details.

于 2013-09-30T22:07:24.257 回答