根据换行拆分CLOB列-Oracle SQL

时间:2019-05-04 12:57:34

标签: sql regex oracle

我有一张桌子

表1

f_name     f_content
test1.txt  YL*1**50*1~
           RX*1~
           LR*2~
test2.txt  YL*1**49*1~
           EE*1~
           WW*2~
  • f_content是CLOB
  • f_name是varchar2(4000)

我写了这个SQL:

SELECT
    d.*,
    c.line_num,
    translate(substr(d.f_content, part1 + 1, part2 - part1), ' ~'
                                                                || CHR(10)
                                                                || CHR(13), ' ') line
FROM
    table1 d
    CROSS JOIN LATERAL (
        SELECT
            level   line_num,
            DECODE(level, 1, 0, regexp_instr(d.f_content, '~', 1, level - 1)) part1,
            DECODE(regexp_instr(d.f_content, '~', 1, level), 0, length(d.f_content), regexp_instr(d.f_content, '~', 1, level
            )) part2
        FROM
            dual
        CONNECT BY
            level <= regexp_count(d.f_content, '~ ')
    ) c;

我的预期输出是:

f_name     f_content        line_num    line
test1.txt  YL*1**50*1~      1           YL*1**50*1
           RX*1~
           LR*2~
test1.txt  YL*1**50*1~      2           RX*1
           RX*1~
           LR*2~
test1.txt  YL*1**50*1~      3           LR*2
           RX*1~
           LR*2~


test2.txt  YL*1**49*1~      1           YL*1**49*1
           EE*1~
           WW*2~
test2.txt  YL*1**49*1~      2           EE*1
           EE*1~
           WW*2~
test2.txt  YL*1**49*1~      3           WW*2
           EE*1~
           WW*2~

但是在基于上述SQL的输出中,我只得到line_num =1。

如何使SQL代码正常工作,以便给出所有代码?

1 个答案:

答案 0 :(得分:1)

您可以使用没有hierarchical query条件的JOIN

select t1.*, level as line_num, 
       regexp_replace( regexp_substr( t1.f_content,'[^~]+', 1, level), '(^[[:space:]]+)' ) 
       as line
  from table1 t1
 connect by level <= regexp_count(f_content, '~')   
    and prior f_name = f_name
    and prior sys_guid() is not null

Demo