如何在Oracle中将字符串拆分为多行?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (22)

我知道这已经在一定程度上用PHP和MYSQL回答了,但我想知道是否有人能教我在Oracle 10g(最好)和11g中将字符串(逗号分隔)分割成多行的最简单方法。

表格如下:

Name | Project | Error 
108    test      Err1, Err2, Err3
109    test2     Err1

我想创建以下内容:

Name | Project | Error
108    Test      Err 1
108    Test      Err 2 
108    Test      Err 3 
109    Test2     Err1
提问于
用户回答回答于

正则表达式:

with temp as  (
       select 108 Name, 'test' Project, 'Err1, Err2, Err3' Error  from dual
       union all
       select 109, 'test2', 'Err1' from dual
     )

SELECT distinct Name, Project, trim(regexp_substr(str, '[^,]+', 1, level)) str
  FROM (SELECT Name, Project, Error str FROM temp) t
CONNECT BY instr(str, ',', 1, level - 1) > 0
order by Name
用户回答回答于

with temp as
(
    select 108 Name, 'test' Project, 'Err1, Err2, Err3' Error  from dual
    union all
    select 109, 'test2', 'Err1' from dual
)
select distinct
  t.name, t.project,
  trim(regexp_substr(t.error, '[^,]+', 1, levels.column_value))  as error
from 
  temp t,
  table(cast(multiset(select level from dual connect by  level <= length (regexp_replace(t.error, '[^,]+'))  + 1) as sys.OdciNumberList)) levels
order by name

扫码关注云+社区