2

我有两张桌子。

派对名单

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

我想调用一个可以将值插入两个表的函数。我的输出应该是这样的。 派对列表表

 | 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;');

是否有way to split列表项(整数)list table并在循环中调用插入查询?

4

1 回答 1

1

您可以使用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 小提琴演示

实际上,可以将此函数编写为 SQL 而不是 plpgsql,如您所见,它只是一个语句。

于 2013-08-26T11:13:11.913 回答