Re: Looping through arrays

From: Joe Conway <mail(at)joeconway(dot)com>
To: robert(at)webtent(dot)com
Cc: PostgreSQL <pgsql-general(at)postgresql(dot)org>
Subject: Re: Looping through arrays
Date: 2005-11-04 06:59:00
Message-ID: 436B06B4.6030806@joeconway.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Robert Fitzpatrick wrote:
> I have a field with 'AA-BB-CC-DD' and I want to pull those four values
> into an array and then loop through the array inserting records into a
> table for each element. Can you someone point me to an example of this
> in pl/pgsql?
>

Something like this?

create table testfoo (id int, arrstr text);
create table testfoo_det (id int, elem text);
insert into testfoo values (1, 'AA-BB-CC-DD');
insert into testfoo values (2, 'EE-FF-GG-HH');

create or replace function testfoo_func(int) returns void as $$
declare
arrinp text[];
begin
select into arrinp string_to_array(arrstr,'-')
from testfoo where id = $1;

for i in array_lower(arrinp, 1)..array_upper(arrinp, 1) loop
execute 'insert into testfoo_det
values (' || $1 || ', ''' || arrinp[i] || ''')';
end loop;

return;

end;
$$ language plpgsql;

regression=# select testfoo_func(id) from testfoo;
testfoo_func
--------------

(2 rows)

regression=# select * from testfoo_det;
id | elem
----+------
1 | AA
1 | BB
1 | CC
1 | DD
2 | EE
2 | FF
2 | GG
2 | HH
(8 rows)

HTH,

Joe

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Joe Conway 2005-11-04 07:09:08 Re: Array Values and References
Previous Message MaXX 2005-11-04 06:44:08 Re: Changing ids conflicting with serial values?