pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Leif Biberg Kristensen <leif@solumslekt.org>
To: postgresql <pgsql-sql@postgresql.org>
Subject: Re: Plpgsql: Iterating through a string of parameters
Date: Thu, 25 Mar 2010 17:00:25 +0100
Message-ID: <201003251700.25623.leif@solumslekt.org> (raw)
In-Reply-To: <201003251616.53097.leif@solumslekt.org>
References: <201003251616.53097.leif@solumslekt.org>

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/



view thread (3+ messages)  latest in thread

Message-ID: <201003251700.25623.leif@solumslekt.org>
Permalink:  ../201003251700.25623.leif@solumslekt.org/
Also on:    postgresql.org/message-id/201003251700.25623.leif@solumslekt.org

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: leif@solumslekt.org
  Subject: Re: Plpgsql: Iterating through a string of parameters
  In-Reply-To: <201003251700.25623.leif@solumslekt.org>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox