【问题标题】:Oracle - text parsingOracle - 文本解析
【发布时间】:2018-04-12 14:17:30
【问题描述】:

有人可以帮我解析 Oracle 数据库中字符串列的子字符串吗?

我有 2 列需要从数据库中获取,例如:

ID     STRING
425    22 23
416    1 22
682    1 22
688    11 133
703    22 12
707    1
710    1 22 12
715    1
716    1 12
796    333
740    1 22 12

我需要提取每个由“空格”分隔的子字符串,将其与正确的ID连接并放入一个新表中,例如:

enter code here
ID:    SUBSTRING
425    22
425    23
416    1
416    22
425    22
425    23

我需要假设我不知道STRING 列中子字符串的数量。

我尝试过这样的事情,但它复制了输出记录:

select ID,
regexp_substr(string,'[^ ]+',1,level),
from (select ID, STRING from TABLE   
where regexp_substr(STRING,'[^ ]+',1,level) is not null
CONNECT BY ID = ID 
and regexp_substr(STRING,'[^ ]+',1,level) is not null

【问题讨论】:

  • 您是否只需要提取至少包含一个空格的子字符串,或者也可以提取其中不包含空格的字符串(原样)?
  • 对我来说,每个子字符串里面都没有空格符号。只需要提取用空格符号分隔的所有子字符串。每个子字符串都需要与所取行的 ID 连接。
  • 检查我的答案,让我知道它是否有效。请阅读:stackoverflow.com/help/someone-answers.

标签: sql oracle split substr


【解决方案1】:

其中一种方法:

with test_table as (
  select 425 id, '22 23' str from dual union all
  select 416   , '1 22'      from dual union all
  select 682   , '1 22'      from dual union all
  select 688   , '11 133'    from dual union all
  select 703   , '22 12'     from dual union all
  select 707   , '1'         from dual union all
  select 710   , '1 22 12'   from dual union all
  select 715   , '1'         from dual union all
  select 716   , '1 12'      from dual union all
  select 796   , '333'       from dual union all
  select 740   , '1 22 12'   from dual ),
xml_table as (
  select id, 
         xmltype('<main><str>' || regexp_replace(str, ' +', '</str><str>') || '</str></main>') xml
    from test_table)
select id,
       extractValue(value(t),'str') result
from xml_table s,
     table(XMLSequence(s.xml.extract('main/str'))) t;
;

【讨论】:

    【解决方案2】:

    您可以使用DISTINCT 或使用SYS_GUID() 方法。

    SELECT ID
        ,REGEXP_SUBSTR(string, '[^ ]+', 1, LEVEL) AS substring
    FROM TABLE1 CONNECT BY LEVEL <= REGEXP_COUNT(STRING, '[^ ]+')
        AND PRIOR ID = ID
        AND PRIOR SYS_GUID() IS NOT NULL
    

    阅读这篇文章了解它的工作原理:https://community.oracle.com/thread/2526535

    Fiddle demo

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2020-05-03
    • 1970-01-01
    • 2021-09-20
    • 2011-11-20
    • 1970-01-01
    • 2013-07-28
    相关资源
    最近更新 更多