sql - How to split a list of values into a variable and how to make a insert function work under a for each loop in postgreSQL -
i having 2 tables.
partylist
create table partylist ( sno serial not null, party_title text, party_venue text, party_date date, party_list character varying, amount_list text );
list
create table list( sno integer, participant_name text, amount_paid integer );
this full sql fiddle.
i want call function can insert values both tables. , output should . partylist table
| sno | party_title | party_venue | party_date | party_list | |amount_list --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 1 | games | indoor stadium | august, 10 2013 00:00:00+0000 | ronald;sania;sachin;pointing;samueal;gibbs;gayle;smith; | 100;200;100;100;200;100;100;100; | | 2 | dance | stage | august, 15 2013 00:00:00+0000 | micheal jakson; britney ; daddy yankee; ar rehaman; jestin bebber; |200;100;100;200;100; |
list table
| sno | participant_name | amount_list --------------------------------------- | 1 | ronald | 100 | 1 | sania | 200 | 1 | sachin | 100 | 1 | pointing | 100 | 1 | samueal | 200 | 1 | gibbs | 100 | 1 | gayle | 100 | 1 | smith | 100 | 2 | micheal jakson | 200 | 2 | britney | 100 | 2 | daddy yankee | 100 | 2 | ar rehaman | 200 | 2 | jestin bebber | 100
when call function these values in example below.
insert_function('games','indoor stadium','08-10-2013','ronald;sania;sachin;pointing;samueal;gibbs;gayle;smith;','100;200;100;100;200;100;100;100;'), ('dance','stage','08-15-2013','micheal jakson; britney ; daddy yankee; ar rehaman; jestin bebber;','200;100;100;200;100;');
is there way split
list items (integer) , call insert query of list table
in loop ?
you can use regexp_split_to_table function:
create or replace function insert_party( _title text, _venue text, _date date, _list text, _amount_list text ) returns void $body$ begin cte ( insert partylist(party_title, party_venue, party_date, party_list, amount_list) values (_title, _venue, _date, _list, _amount_list) returning sno ), cte2 ( select sno, regexp_split_to_table(_list, ';') participant_name, regexp_split_to_table(_amount_list, ';') amount_paid cte ) insert list (sno, participant_name, amount_paid) select sno, participant_name, amount_paid::int cte2 participant_name not null , participant_name <> ''; end; $body$ language 'plpgsql' volatile cost 100;
actually, it's possible write function sql , not plpgsql, see, it's 1 statement.
Comments
Post a Comment