create table MY_CHANGE (MY_ID int,
MY_VALUE varchar(100));
insert into MY_CHANGE values(1,'a,b,c');
insert into MY_CHANGE values(2,'d,r');
insert into MY_CHANGE values(3,'x,y,z');
commit;
所謂的一行變多行就是要實現下面的效果:
1 a
1 b
1 c
2 d
2 r
3 x
3 y
3 z
pl/sql:
declare num int; --判斷表是否存在的標識
cur_my_ID int; --遊標變量值
cur_my_value varchar2(100); --遊標變量值
s1 varchar(100);
s2 varchar(100); --s1,s2爲拆分做準備
len_1 int; --字符串長度
cursor cur_my is
select my_ID,my_value from my_change; --定義遊標
begin
/*
* 存在表MY_TABLE則刪除,不存在則創建
*/
select count(1) into num from all_tables where TABLE_NAME = 'MY_TABLE' and OWNER='SCOTT';
if(num=1) then
execute immediate 'drop table MY_TABLE';
end if;
execute immediate '
create table MY_TABLE(
my_ID int,
my_value_now varchar2(100))';
open cur_my;
fetch cur_my into cur_my_id,cur_my_value;
while cur_my%found
loop --外循環,遊標取值
select replace(cur_my_value,',','') into s1 from dual; -- 去除字符中間的 ,
select length(s1) into len_1 from dual; -- 取當前字符串長度
while len_1>0 --內循環,拆分數據
loop
s2:=substr(s1,1,1); -- 取出第一個字符
insert into my_table values(cur_my_id,s2); --插入
s1:=substr(s1,2,len_1-1); -- 把第一個字符刪除
len_1:=len_1-1; -- 循環次數-1
end loop;
fetch cur_my into cur_my_id,cur_my_value;
end loop;
close cur_my;
end ;
存儲過程:
create or replace
procedure cc as
num int; --判斷表是否存在
cur_my_ID int; --遊標值
cur_my_value varchar2(100); --遊標值
s1 varchar(100);
s2 varchar(100);
len_1 int;
cursor cur_my is
select my_ID,my_value from my_change;
str_sql varchar2(500);
tb_name varchar2(100);
begin
tb_name:='MY_TABLE';
select count(1) into num from all_tables where TABLE_NAME = 'MY_TABLE' and OWNER='SCOTT';
if(num=1) then
str_sql:='drop table '|| tb_name;
execute immediate str_sql;
end if;
str_sql:=' create table '|| tb_name ||' (
my_ID int,
my_value_now varchar2(100))';
execute immediate str_sql;
open cur_my;
fetch cur_my into cur_my_id,cur_my_value;
while cur_my%found
loop
select replace(cur_my_value,',','') into s1 from dual; -- 去除字符中間的 ,
select length(s1) into len_1 from dual; -- 取當前字符串長度
while len_1>0
loop
s2:=substr(s1,1,1); -- 取出第一個字符
str_sql:='insert into '|| tb_name|| '(my_ID,my_value_now) values(' || cur_my_id ||','''|| s2 ||''')'; --兩個單引號輸出單引號
execute immediate str_sql;
-- dbms_output.put_line(s2); -- 輸出
s1:=substr(s1,2,len_1-1); -- 把第一個字符刪除
len_1:=len_1-1; -- 循環次數-1
end loop;
fetch cur_my into cur_my_id,cur_my_value;
end loop;
close cur_my;
end cc;