Oracle将文本拆分为列

时间:2014-05-28 11:02:13

标签: oracle split

我搜索了论坛,但我找不到我想要的答案。

我的数据库中有一个很长的varchar2。我需要通过|。

拆分

示例:HEADER | 20140528 | 3407

所以,我写了一个这样的查询:

select regexp_substr(datas,'[^|]+',1,1) as col_1, 
       regexp_substr(datas,'[^|]+',1,2) as col_2,
       regexp_substr(datas,'[^|]+',1,3) as col_3
from temp_gerben

但是,第二个值可能是空白。在这种情况下,该行看起来像: HEADER || 3407

但同样的查询并没有很好地处理这个问题。忽略第二个字段很简单,并将第三个字段放在其中。

由于我需要为不同的报告分配这些数据,我需要它将该字段保持为空而不是忽略。

1 个答案:

答案 0 :(得分:2)

问题是你的正则表达式正在寻找至少一个非|字符,而你的表达式中没有。解决此问题的一种方法是添加这样一个字符:

select regexp_substr(replace(datas, '||', '| |'), '[^|]+', 1, 1) as col_1, 
       regexp_substr(replace(datas, '||', '| |'), '[^|]+', 1, 2) as col_2,
       regexp_substr(replace(datas, '||', '| |'), '[^|]+', 1, 3) as col_3
from (select 'HEADER|20140528|3407' as datas from dual union all
      select 'HEADER||3407' from dual
     ) temp_gerben;

另一种方法是使用*代替+来搜索分隔字符。这不是很有效,因为计数开始了。您可以通过在字符串的末尾添加|,查找与|结尾的模式,然后删除|

来使其有效
select replace(regexp_substr(datas || '|', '[^|]*[|]', 1, 1), '|', '') as col_1, 
       replace(regexp_substr(datas || '|', '[^|]*[|]', 1, 2), '|', '') as col_2,
       replace(regexp_substr(datas || '|', '[^|]*[|]', 1, 3), '|', '') as col_3
from (select 'HEADER|20140528|3407' as datas from dual union all
      select 'HEADER||3407' from dual
     ) temp_gerben;