Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through split string

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;
like image 239
bqui56 Avatar asked Sep 29 '13 17:09

bqui56


2 Answers

you should add word 'array' before actual array:

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

sql fiddle demo

documentation about looping through arrays.

like image 146
Roman Pekar Avatar answered Nov 09 '22 23:11

Roman Pekar


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.

like image 39
Erwin Brandstetter Avatar answered Nov 10 '22 00:11

Erwin Brandstetter