将分隔字符串转换为列时保留顺序

时间:2013-09-17 15:22:20

标签: sql oracle oracle11g

我想保留记录顺序,以逗号分隔的字符串形式提供。分隔字符串中的5 th 项为null。我还需要5 th 行为空。

 with test as 
(select 'ABC,DEF,GHI,JKL,,MNO' str from dual  
  )  
  select rownum, regexp_substr (str, '[^,]+', 1, rownum) split  
    from test  
 connect by  level <= length (regexp_replace (str, '[^,]+' ))  + 1

我得到的当前结果将其置于6 th 位置:

1   ABC
2   DEF
3   GHI
4   JKL
5   MNO
6   

3 个答案:

答案 0 :(得分:3)

您的表达式保留了 顺序,但您的正则表达式无法正确匹配空值,因此第5项消失。第6行是NULL,因为在第5场比赛后没有更多匹配。

你可以这样做:

SQL> with test as
  2  (select 'ABC,DEF,GHI,JKL,,MNO' str from dual
  3    )
  4  SELECT rownum,
  5         rtrim(regexp_substr(str || ',', '[^,]*,', 1, rownum), ',') split
  6    FROM test
  7  CONNECT BY LEVEL <= length(regexp_replace(str, '[^,]+')) + 1;

    ROWNUM SPLIT
---------- ---------------------------------------------------------------
         1 ABC
         2 DEF
         3 GHI
         4 JKL
         5 
         6 MNO

6 rows selected

或者这个:

SQL> with test as
  2  (select 'ABC,DEF,GHI,JKL,,MNO' str from dual
  3    )
  4  SELECT rownum,
  5         regexp_substr(str, '([^,]*)(,|$)', 1, rownum, 'i', 1) split
  6    FROM test
  7  CONNECT BY LEVEL <= length(regexp_replace(str, '[^,]+')) + 1;

    ROWNUM SPLIT
---------- ------------------------------------------------------------
         1 ABC
         2 DEF
         3 GHI
         4 JKL
         5 
         6 MNO

6 rows selected

答案 1 :(得分:0)

尝试这样的事情:

SELECT
      STR,
      REPLACE ( SUBSTR ( STR,
                     CASE LEVEL
                         WHEN 1
                         THEN
                             0
                         ELSE
                             INSTR ( STR,
                                    '~',
                                    1,
                                    LEVEL
                                    - 1 )
                     END
                     + 1,
                     1 ),
              '~' )
FROM
      (SELECT 'A~~C~~E' AS STR FROM DUAL)
CONNECT BY
      LEVEL <= LENGTH ( REGEXP_REPLACE ( STR,
                                  '[^~]+' ) )
             + 1;

答案 2 :(得分:0)

这个有效..

SELECT
      ROWNUM,
      CAST ( REGEXP_SUBSTR ( STR,
                        '(.*?)(,|$)',
                        1,
                        LEVEL,
                        NULL,
                        1 ) AS CHAR ( 12 ) )
          OUTPUT
FROM
      (SELECT 'ABC,DEF,GHI,JKL,,MNO' AS STR FROM DUAL)
CONNECT BY
      LEVEL <= REGEXP_COUNT ( STR,
                         ',' )
             + 1;