现有A表和B表,有bill_id,detail_data两个字段,其中bill_id为数字型,是用户手机号码;detail_data是个字符串总长度为4000,每16位是一组,每组由两部分组成,费用代码(7位)和费用(9位)(注:位数包括空格),多个组拼成该字段的内容。现要将A表中的bill_id和B表的bill_id相等的记录,将其detail_data合入B表中的detail_data,原则是费用代码相同的,将费用相加,A表中有但B表中没有的费用代码,将费用代码和费用追加到B表的detail_data中。
写出存储过程。
create or replace procedure test_sp_afa
is
ls_detail_data varchar2(4000);
cursor c1 is select a.bill_id from a, b where a.bill_id=b.bill_id;
begin
for iii in c1 loop
--拆分b表,写入test_b(这个过度表很恶心)
insert into test_b
select substr(detail_data,rownum*16-15,7) daima0,substr(detail_data,rownum*16-15,9) feiy00
from b
start with bill_id=iii.bill_id
connect by bill_id=iii.bill_id and rownum<=ceil(length(trim(detail_data))/16);
--拆分a表,和test_b连接.
merge into test_b bb
using (
select substr(detail_data,rownum*16-15,7) daima0,substr(detail_data,rownum*16-15,9) feiy00
from a
start with bill_id=iii.bill_id
connect by bill_id=iii.bill_id and rownum<=ceil(length(trim(detail_data))/16)
) aa
on (aa.daima0=bb.daima0)
when matched then
update set bb.feiy00+aa.feiy00
when not matched then
insert values (aa.daima0,aa.feiy00);
--取连接后的detail_data 值
select max(detail_data) into ls_detail_data
from
(
select replace(sys_connect_by_path(rpad(daima0,7,' ')||rpad(feiy00,9,' '),','),',') detail_data
from
(select a.*,rownum rn
from test_b a )
start with rn=1
connect by rn=prior rn+1
);
--修改b表对应记录
update b
set detail_data =ls_detail_data
where bill_id=iii.bill_id;
--删除test_b内容
truncate table test_b;
end loop;
--exception
end;