关于一张表中一条记录某个字段进行分割处理后插入到另一张表中多条数据的存储过程写法

问题描述:

     有两张表,表A为原始数据表,表B为结果表。表A结构如下所示,id为主键

   

id      result
1 a*b;c*d;e*f
2 g*h;i*j
3 k*l
4

表B结构如下所示,id和seq为联合主键

id seq num size
1        1 a b
1 2 c d
1 3 e f
2 1 g h
2 2 i j
3 1 k l

 

现在要对表A的数据进行处理,把A表result字段的数据按";"分割成好几条数据后再按"*"分割插入到B表中,结果如B表所示,这个用存储过程怎么实现啊,小弟想了很久想不出,各位有啥好的方法推荐下,拜托了

 

我用的oracle的给你写出来,哎,没写过存储过程的孩子伤不起啊,真心麻烦,还是java好使,能多给点分就多给点吧。。

[code="sql"]
declare
sub_str varchar2(4000);
insert_str varchar2(4000);
seq int := 0;
pos1 int := 1;
pos2 int := 1;
cursor c is
select * from a;
r c%rowtype;
begin
open c;
--using loop to get the searching result
loop
fetch c
into r;
exit when c%notfound;
--init pos1,pos2
pos1 := 1;
pos2 := 1;
seq := 0;
while pos2 != 0 and pos1 <= length(r.result) loop
pos2 := instr(r.result, ';', pos1);
seq := seq + 1;
--judge the pos2 ,if equals zero means that the searching get end
if pos2 != 0 then
sub_str := substr(r.result, pos1, pos2 - pos1);
else
sub_str := substr(r.result, pos1);
end if;
--e.g. insert into B (id,seq,num,space) values (1,1,'a','b')
insert_str := 'insert into B (id,seq,num,space) values ('
|| r.id || ',' || seq || ',' ||chr(39)||
substr(sub_str, 1, instr(sub_str, '*')-1) ||chr(39)|| ','||chr(39) ||
substr(sub_str, instr(sub_str, '*') + 1) ||chr(39)|| ')' ;
--dbms_output.put_line(insert_str);
execute immediate insert_str;
-- next search position add 1
pos1 := pos2 + 1;
end loop;
end loop;

close c;
commit;
end;
[/code]

数据库字符串不好处理用程序处理呗

oracle 吗

a×b 中 a和b都是固定一位吗?如果是算法更简单啊