如何通过分割字符串进行循环

时间:2022-12-28 21:43:14

How can I split a string on some delimiter and then loop through the parts? I tried a few functions and loop types with no success. I am trying to achieve something like:

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

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;

2 个解决方案

#1


6  

you should add word 'array' before actual array:

您应该在实际的数组之前添加单词'array':

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

sql fiddle demo

sql小提琴演示

documentation about looping through arrays.

关于通过数组循环的文档。

#2


0  

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:

如果您可以根据基于集合的操作(纯SQL查询)来重新调整您的问题,那么您应该这样做。unnest()是键集返回函数。也可以封装在sql或plpgsql函数中。plpgsql语法:

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

Details depend on your details.

细节取决于你的细节。

#1


6  

you should add word 'array' before actual array:

您应该在实际的数组之前添加单词'array':

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

sql fiddle demo

sql小提琴演示

documentation about looping through arrays.

关于通过数组循环的文档。

#2


0  

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:

如果您可以根据基于集合的操作(纯SQL查询)来重新调整您的问题,那么您应该这样做。unnest()是键集返回函数。也可以封装在sql或plpgsql函数中。plpgsql语法:

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

Details depend on your details.

细节取决于你的细节。