oracle按空格拆分列,DB2字符串按照指定符号进行拆分成多个字段的实现方式

--假设我现在有这样一张表

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值