You don't need a loop or PL/pgSQL for this. You can do this with a single statement:
Assuming the following setup:
create table tablename
(
id integer primary key,
country_list text
);
create table lookup
(
iso_code varchar(3),
country text
);
insert into tablename
values
(1, 'Germany, Austria, Italy'),
(2, 'Austria, France'),
(3, 'France, Switzerland');
insert into lookup
values
('de', 'Germany'),
('at', 'Austria'),
('it', 'Italy'),
('fr', 'France'),
('ch', 'Switzerland');
You can unnest the countries using:
select s.id, trim(unnest(string_to_array(s.country_list, ','))) as country
from tablename s;
Given the sample data above that returns the following:
id | country
---+------------
1 | Germany
1 | Austria
1 | Italy
2 | Austria
2 | France
3 | France
3 | Switzerland
This can be joined to your lookup table:
with normalized as (
select s.id, trim(unnest(string_to_array(s.country_list, ','))) as country
from tablename s
)
select n.id, n.country, l.iso_code
from normalized n
join lookup l on l.country = n.country;
This returns the following:
id | country | iso_code
---+-------------+---------
1 | Austria | at
1 | Germany | de
1 | Italy | it
2 | Austria | at
2 | France | fr
3 | France | fr
3 | Switzerland | ch
You can aggregate the list of ISO codes back into your de-normalized structure:
with normalized as (
select s.id, trim(unnest(string_to_array(s.country_list, ','))) as country
from tablename s
)
select n.id, string_agg(l.iso_code,',') as iso_list
from normalized n
join lookup l on l.country = n.country
group by n.id;
And that can be used to replace the values in the target table:
with normalized as (
select s.id, trim(unnest(string_to_array(s.country_list, ','))) as country
from tablename s
), translated as (
select n.id, string_agg(l.iso_code,',') as iso_list
from normalized n
join lookup l on l.country = n.country
group by n.id
)
update tablename st
set country_list = t.iso_list
from translated t
where t.id = st.id;
After that the contents of tablename
is:
id | country_list
---+-------------
1 | it,at,de
2 | fr,at
3 | fr,ch
A much better solution would be to properly normalize your model and create a many-to-many mapping table between tablename
and the lookup_table