oracle pl/sql level妙用

本文介绍了如何在Oracle数据库中将带有特定分隔符的字符串转换为列表形式的数据列。包括使用LEVEL关键字处理规则字符串,以及利用正则表达式函数处理不规则字符串的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载网址:http://blog.youkuaiyun.com/evildog/article/details/8903724

该文章仅用于记事本保留,大家也可以看

1、当需要把一个字符串按某一分隔符分隔后,变为数据列,即把字符串行变为列,可以使用level关键字,例子:

 

[sql]  view plain  copy
  1. with t as  
  2.  (select 'a;b;c;d;e' as str from dual)  
  3. select level,  
  4.        t.str,  
  5.        substr(t.str, 2 * (level - 1) + 1, 1) as str_signle  
  6.   from t  
  7. connect by level <= length(t.str) - length(replace(t.str, ';''')) + 1;  

 

运行结果:

 

2、上面的写法只是适用于一般有规律的字符串行,当遇到不规则字符串行时,可以使用Oracle的正则表达式函数,请看下面的例子:

 

[sql]  view plain  copy
  1. with t as  
  2.  (select 'i;am;a;test;hahahhah' as str from dual)  
  3. select level,  
  4.        str,  
  5.        regexp_substr(t.str, '[^;]+', 1, level) str_single  
  6.   from t  
  7. connect by level <= length(t.str) - length(replace(t.str, ';''')) + 1;  

 

运行结果:

或者不使用正则表达式:

 

[sql]  view plain  copy
  1. with t_org as  
  2.  (select 'I am a complicated string' as str from dual),  
  3. t_sep as  
  4.  (select ' ' as sep from dual),  
  5. as  
  6.  (select t_org.str as orign_str,  
  7.          t_sep.sep || t_org.str || t_sep.sep as str  
  8.     from t_org,  
  9.          t_sep)  
  10. select level,  
  11.        t.orign_str,  
  12. /*     instr(t.str, t_sep.sep, 1, levelas separator_postion,  
  13.        instr(t.str, t_sep.sep, 1, level) + 1 as str_postion_begin,  
  14.        instr(t.str, t_sep.sep, 1, level + 1) -  
  15.        instr(t.str, t_sep.sep, 1, level) - 1 as str_single_len,*/  
  16.        substr(t.str, instr(t.str, t_sep.sep, 1, level) + 1, instr(t.str, t_sep.sep, 1, level + 1) -  
  17.                instr(t.str, t_sep.sep, 1, level) - 1) as str_signle  
  18.   from t,  
  19.        t_sep  
  20. connect by level < length(t.str) - length(replace(t.str, t_sep.sep, ''));  

 

运行结果:


 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值