--假设我现在有这样一张表
create table test_col
(
colt varchar(200)
);
--假设表里面有这样的一些数据
insert into test_col
select '123;qweq;czxcd;fasdf;564;fdsa' as colt from sysibm.dual union all
select 'dfas;fdsaf' from sysibm.dual;
commit;
select * from test_col;
--需要拆分的最大列数目
--原理:串的最大长度 减去 将分号除去之后的长度 的到 分号的数量 在 加上1 即为需要拆分成的字段的数量
select max(length(colt)-length(replace(colt,';','')))+1 from test_col;
--instr函数用法介绍
--instr('某个串','要寻找的串或者字符',m,n)
--表示 要寻找的串或者字符 在 某个串 中从第m个位置开始查找 第n次出现的位置
select a.colt,
instr(a.colt,';',1,1) as fst,--分号第1次出现的位置
instr(a.colt,';',1,2) as sec,--分号第2次出现的位置
instr(a.colt,';',1,3) as thi,--分号第3次出现的位置
instr(a.colt,';',1,4) as fou,--分号第4次出现的位置
instr(a.colt,';',1,5) as fif,--分号第5次出现的位置
instr(a.colt,';',1,6) as six --分号第6次出现的位置
from test_col a;
--substr('某个串',m,n)
--表示 将 某个串 从 第m个位置开始 截取n个字符的长度
--若这里n不填 则表示从第m个位置一直截取到最后
--eg: substr('abcd',2,2) --> bc
select a.colt,
case when instr(a.colt,';',1,1) <> 0 then
substr(a.colt,1,instr(a.colt,';',1,1)-1)
else substr(a.colt,1)
end as fst,
case when instr(a.colt,';',1,2) <> 0 and instr(a.colt,';',1,1) <> 0 then
substr(a.colt,instr(a.colt,';',1,1)+1,instr(a.colt,';',1,2)-instr(a.colt,';',1,1)-1)
when instr(a.colt,';',1,2) = 0 and instr(a.colt,';',1,1) <> 0 then
substr(a.colt,instr(a.colt,';',1,1)+1)
else ''
end as sec,
case when instr(a.colt,';',1,3) <> 0 and instr(a.colt,';',1,2) <> 0 then
substr(a.colt,instr(a.colt,';',1,2)+1,instr(a.colt,';',1,3)-instr(a.colt,';',1,2)-1)
when instr(a.colt,';',1,3) = 0 and instr(a.colt,';',1,2) <> 0 then
substr(a.colt,instr(a.colt,';',1,2)+1)
else ''
end as thi,
case when instr(a.colt,';',1,4) <> 0 and instr(a.colt,';',1,3) <> 0 then
substr(a.colt,instr(a.colt,';',1,3)+1,instr(a.colt,';',1,4)-instr(a.colt,';',1,3)-1)
when instr(a.colt,';',1,4) = 0 and instr(a.colt,';',1,3) <> 0 then
substr(a.colt,instr(a.colt,';',1,3)+1)
else ''
end as fou,
case when instr(a.colt,';',1,5) <> 0 and instr(a.colt,';',1,4) <> 0 then
substr(a.colt,instr(a.colt,';',1,4)+1,instr(a.colt,';',1,5)-instr(a.colt,';',1,4)-1)
when instr(a.colt,';',1,5) = 0 and instr(a.colt,';',1,4) <> 0 then
substr(a.colt,instr(a.colt,';',1,4)+1)
else ''
end as fiv,
case when instr(a.colt,';',1,6) <> 0 and instr(a.colt,';',1,5) <> 0 then
substr(a.colt,instr(a.colt,';',1,5)+1,instr(a.colt,';',1,6)-instr(a.colt,';',1,5)-1)
when instr(a.colt,';',1,6) = 0 and instr(a.colt,';',1,4) <> 0 then
substr(a.colt,instr(a.colt,';',1,5)+1)
else ''
end as six
from test_col a;