我有两张 table 。
派对列表
create table partyList
(
sno serial NOT NULL,
Party_title text,
Party_venue text,
Party_date date,
Party_list character varying,
Amount_list text
);
列表
create table list(
sno integer,
participant_name text,
amount_paid integer
);
这是完整的 SQL FIDDLE .
我想调用一个可以将值插入两个表的函数。 我的输出应该是这样的。 partyList 表
| 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; |
列表
| 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
当我通过这些值调用我的函数时,如下例所示。
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;');
有没有办法拆分
列表项(INTEGER)并循环调用列表表
的插入查询?
最佳答案
你可以使用regexp_split_to_table功能:
CREATE OR REPLACE FUNCTION insert_party(
_title text, _venue text, _date date,
_list text, _Amount_list text
)
RETURNS void AS
$BODY$
begin
with cte as (
insert into partyList(Party_title, Party_venue, Party_date, Party_list, Amount_list)
values (_title, _venue, _date, _list, _Amount_list)
returning sno
), cte2 as (
select
sno,
regexp_split_to_table(_list, ';') as participant_name,
regexp_split_to_table(_Amount_list, ';') as amount_paid
from cte
)
insert into list (sno, participant_name, amount_paid)
select sno, participant_name, amount_paid::int
from cte2
where participant_name is not null and participant_name <> '';
end;
$BODY$
LANGUAGE 'plpgsql' VOLATILE
COST 100;
实际上,可以将此函数编写为 SQL 而不是 plpgsql,如您所见,它只是一条语句。
关于sql - 如何将值列表拆分为变量以及如何使插入函数在 postgreSQL 中的 for each 循环下工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18442204/