Re: Plpgsql: Iterating through a string of parameters

From: Leif Biberg Kristensen <leif(at)solumslekt(dot)org>
To: postgresql <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Plpgsql: Iterating through a string of parameters
Date: 2010-03-25 16:00:25
Message-ID: 201003251700.25623.leif@solumslekt.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Thursday 25. March 2010 16.16.53 Leif Biberg Kristensen wrote:
> I'm struggling with how to make plpgsql iterate through a list of numbers
> input as a text string, eg. "1438 2656 973 4208". I figure that I can use the
> regexp_split_to_array() function to make an array of the string, but can I
> iterate through an array with eg. a FOR loop?

I found a solution myself through trial-and-error:

CREATE OR REPLACE FUNCTION text_to_arr(TEXT) RETURNS VOID AS $$
DECLARE
arr TEXT ARRAY;

BEGIN
arr := regexp_split_to_array($1, E'\\s+');
FOR i IN 1..array_length(arr, 1) LOOP
RAISE NOTICE '%', arr[i]::INTEGER;
END LOOP;
RETURN;
END
$$ LANGUAGE plpgsql IMMUTABLE;

pgslekt=> select * from text_to_arr('1438 2607 1504');
NOTICE: 1438
NOTICE: 2607
NOTICE: 1504
text_to_arr
-------------

(1 row)

pgslekt=>

regards,
--
Leif Biberg Kristensen
http://solumslekt.org/

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Greg Stark 2010-03-25 16:05:34 Re: Does IMMUTABLE property propagate?
Previous Message Leif Biberg Kristensen 2010-03-25 15:16:53 Plpgsql: Iterating through a string of parameters