如何在 Oracle 中使用 , 和 : 分隔符将 CLOB 对象拆分为多个记录

Ush*_*sha 1 regex oracle substr oracle12c regexp-substr

我有一个 CLOB 对象示例,如下所示。我想首先使用分隔符“,”将其拆分,并将其保存在临时表中以备后用。

ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0
Run Code Online (Sandbox Code Playgroud)

我想在每一行中以以下格式保存结果。

Column_Name
__________________________
ABCDEF:PmId12345RmLn1VlId0
ABCDEF:PmId12345RmLn1VlId0
ABCDEF:PmId12345RmLn1VlId0
Run Code Online (Sandbox Code Playgroud)

我尝试使用 REGEXP_SUBSTR 函数

select 
    regexp_substr('ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0', '[^,]+', 1, 1) Column_Name 
from dual;
Run Code Online (Sandbox Code Playgroud)

上面的查询给了我如下的单条记录

Column_Name
__________________________
ABCDEF:PmId12345RmLn1VlId0
Run Code Online (Sandbox Code Playgroud)

谁能帮我解决这个问题。

mat*_*guy 8

这是使用递归分解子查询(Oracle 11.2 及更高版本)的解决方案:

with inputs ( str ) as (
       select to_clob('ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0,ABCDEF:PmId12345RmLn1VlId0')
       from dual
     ),
     prep ( s, n, token, st_pos, end_pos ) as (
       select ',' || str || ',', -1, null, null, 1
         from inputs
       union all
       select s, n+1, substr(s, st_pos, end_pos - st_pos),
              end_pos + 1, instr(s, ',', 1, n+3)
         from prep
         where end_pos != 0
     )
select n as idx, token as column_name
from   prep
where  n > 0;



   IDX COLUMN_NAME
------ ----------------------------
     1 ABCDEF:PmId12345RmLn1VlId0
     2 ABCDEF:PmId12345RmLn1VlId0
     3 ABCDEF:PmId12345RmLn1VlId0
     4 ABCDEF:PmId12345RmLn1VlId0
     5 ABCDEF:PmId12345RmLn1VlId0
Run Code Online (Sandbox Code Playgroud)

注意事项

您说的是 CLOB,但在您的示例中,您是从 varchar2 字符串中提取的。我添加to_clob()了看看这是否/如何在 CLOB 上工作。

我使用instrsubstr,因为它们经常(通常?)表现得比它们的regexp同类产品更好和更好。

我在输入字符串中保存了每个子字符串的“索引”;在某些情况下,输入字符串中标记的顺序很重要。(虽然不是在您的示例中,您只是将相同的标记重复了五次。)

如果您需要更好的性能,特别是如果您的 CLOB 非常大,则最好使用dbms_lob.substrdbms_lob.instr- 请参阅CLOB 上的 SUBSTR 性能,尤其是 Alex Poole 的回答,以及此处的文档:http : //docs.oracle.com/cd/ B28359_01/appdev.111/b28419/d_lob.htm#BABEAJAD。请注意与常规substr/的语法差异instr