DenisKarakchiev
5/20/2019 - 9:14 AM

Insertin splitted values from comma separated column postgresql

-- inserting
select for_loop_through_query();
-- selecting
select * from temporary_table;
create function for_loop_through_query() returns void
    language plpgsql
as
$$
DECLARE
    rec  RECORD;
    item RECORD;
BEGIN

    FOR rec IN select users.id             as userid,
                      users.name           as username,
                      accounts.name        as account,
                      users.multifonnumber as multifonnumber
               from iris_contact users
                        left join iris_account accounts on users.accountid = accounts.id
               where users.multifonnumber is not null
                 and users.name not like '%Мариуполь%'
        LOOP
            for item in select *
            -- multifonnumber - column that contains comma separated value that needs to split
                        from regexp_split_to_table(rec.multifonnumber, ',')
                loop
                    insert into temporary_table(fio,
                                                account,
                                                multifonnumber)
                    values (rec.username,
                            rec.account,
                            item);
                end loop;

        END LOOP;
END;
$$;
alter function for_loop_through_query() owner to postgres;