bqui56
bqui56

Reputation: 2121

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;

Upvotes: 7

Views: 12224

Answers (2)

Erwin Brandstetter
Erwin Brandstetter

Reputation: 658032

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.

Upvotes: 3

roman
roman

Reputation: 117510

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.

Upvotes: 13

Related Questions