选择以连字符分隔的列到行

70gysomp  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(374)

我有一个以连字符分隔的列,其中包含名称。我要将此列拆分为单个名称行。
我正在使用以下sql:

for t_cur in (select id, names str from table where names is not null) loop
insert into inv value (select id,SPLIT_VALUES,'TOT' from ( select t_cur.id, trim(REGEXP_SUBSTR (t_cur.STR, '[^-]+', 1, LEVEL)) SPLIT_VALUES  FROM dual 
 CONNECT BY LEVEL <= (SELECT LENGTH (REPLACE (t_cur.STR, ',', NULL)) FROM dual
 ) ) where SPLIT_VALUES is not null) ;
 end loop;
end;

问题是有些名字是由。例如,我可以:

Firstname1-secondname1 lastname1 - Firstname2 lastname2 - Firstname3 Lastname3

在这个例子中,我的结果是:

Firstname1
secondname1 lastname1
Firstname2 lastname2 
Firstname3 Lastname3

您能否帮助我使用正确的正则表达式来获得此结果:

Firstname1-secondname1 lastname1
Firstname2 lastname2
Firstname3 Lastname3

解决方案应该是检查char until(空格+hypehen),而不仅仅是(连字符)
谢谢!

xmakbtuz

xmakbtuz1#

有一点帮助 REPLACE 函数将“true”分隔符(空格-破折号-空格)替换为其他分隔符(在我的示例中),它变得简单得多:

SQL> with test (col) as
  2    (select 'Firstname1-secondname1 lastname1 - Firstname2 lastname2 - Firstname3 Lastname3'
  3     from dual
  4    )
  5  select regexp_substr(replace(col, ' - ', '#'), '[^#]+', 1, level) name
  6  from test
  7  connect by level <= regexp_count(replace(col, ' - ', '#'), '#') + 1;
NAME
--------------------------------------------------------------------------
Firstname1-secondname1 lastname1
Firstname2 lastname2
Firstname3 Lastname3

SQL>
v09wglhw

v09wglhw2#

不需要用这种形式的regex替换函数:

WITH TEST (COL) AS
      (SELECT 'Firstname1-secondname1 lastname1 - Firstname2 lastname2 - Firstname3 Lastname3'
       FROM dual
      )
    SELECT REGEXP_SUBSTR(COL, '(.*?)( - |$)', 1, LEVEL, NULL, 1) NAME
    FROM TEST
    CONNECT BY LEVEL <= REGEXP_COUNT(COL, ' - ') + 1;

相关问题