Oracle 拆分字段为行,REGEXP_SUBSTR函数使用笔记记录

函数详细说明请自行百度、Google

查询SQL示例

with t as
 (select '312,564' str, 2 lvl from dual
  union all
  select '123,456,789' str, 3 lvl from dual
  )
select  REGEXP_SUBSTR(str ,'[^,]+', 1, level), lvl STR 
from (
     select str, lvl, rownum rn from t
) CONNECT BY level <= REGEXP_COUNT(str, ',') + 1 
  and rn = prior rn 
  and prior dbms_random.value is not null;

查询结果示例:

str lvl
312 2
564 2
123 3
456 3
789 3

替代SQL示例:

with t as (
     select '123,456,789' str, 3 lvl from dual
     union all
     select '252,741' str, 2 lvl from dual
),
n(str, ori, pos, lvl) as (
       select distinct str || ',', 1, instr(str || ',', ','), lvl from t
       union all
       select str, pos + 1, instr(str, ',', pos + 1), lvl from n
       where instr(str, ',', pos + 1) > 0
)
select substr(str, ori, pos - ori) str, lvl from n;

查询结果示例:

str lvl
123 3
252 2
456 3
741 2
789 3

两种方式执行效率自行验证

你可能感兴趣的:(SQL)