在Oracle中拆分逗号分隔值

时间:2015-02-02 05:43:05

标签: sql oracle regexp-substr

我的数据库中有一列,其值如下:

3862,3654,3828

在虚拟列中任何没有。逗号分隔值可以来。我尝试了以下查询,但它创建了重复的结果。

select regexp_substr(dummy,'[^,]+',1,Level) as dummycol 
  from (select * from dummy_table) 
 connect by level <= length(REGEXP_REPLACE(dummy,'[^,]+'))+1

我不明白这个问题。任何人都可以帮忙吗?

2 个答案:

答案 0 :(得分:3)

完美适合我 -

SQL> WITH dummy_table AS(
  2  SELECT '3862,3654,3828' dummy FROM dual
  3  )
  4  SELECT trim(regexp_substr(dummy,'[^,]+',1,Level)) AS dummycol
  5  FROM dummy_table
  6    CONNECT BY level <= LENGTH(REGEXP_REPLACE(dummy,'[^,]+'))+1
  7  /

DUMMYCOL
--------------
3862
3654
3828

SQL>

还有很多其他方法可以实现它。阅读Split single comma delimited string into rows

更新关于使用列而不是单个字符串值时的重复项。在PRIOR子句中使用DBMS_RANDOM来摆脱循环循环here

尝试以下方法,

SQL> WITH dummy_table AS
  2    ( SELECT 1 rn, '3862,3654,3828' dummy FROM dual
  3    UNION ALL
  4    SELECT 2, '1234,5678' dummy FROM dual
  5    )
  6  SELECT trim(regexp_substr(dummy,'[^,]+',1,Level)) AS dummycol
  7  FROM dummy_table
  8    CONNECT BY LEVEL          <= LENGTH(REGEXP_REPLACE(dummy,'[^,]+'))+1
  9  AND prior rn                 = rn
 10  AND PRIOR DBMS_RANDOM.VALUE IS NOT NULL
 11  /

DUMMYCOL
--------------
3862
3654
3828
1234
5678

SQL>

更新2

另一种方式,

SQL> WITH dummy_table AS
  2    ( SELECT 1 rn, '3862,3654,3828' dummy FROM dual
  3    UNION ALL
  4    SELECT 2, '1234,5678,xyz' dummy FROM dual
  5    )
  6  SELECT trim(regexp_substr(t.dummy, '[^,]+', 1, levels.column_value)) AS dummycol
  7  FROM dummy_table t,
  8    TABLE(CAST(MULTISET
  9    (SELECT LEVEL
 10    FROM dual
 11      CONNECT BY LEVEL <= LENGTH (regexp_replace(t.dummy, '[^,]+')) + 1
 12    ) AS sys.OdciNumberList)) LEVELS
 13    /

DUMMYCOL
--------------
3862
3654
3828
1234
5678
xyz

6 rows selected.

SQL>

答案 1 :(得分:0)

给出一个PL / SQL示例,其中解析具有ID和列名称的表。这将解析并打印出每个ID和解析后的值,然后可以将这些值插入到新表中或以其他方式使用。

输入

public void onPrepared(MediaPlayer player) {
    // Listen for playback completion
    this.player.setOnCompletionListener(this);
    // seek to any location received while not prepared
    //this.seekToPlaying(this.seekOnPrepared);
    // If start playing after prepared
    if (!this.prepareOnly) {
        this.player.start();
        this.setState(STATE.MEDIA_RUNNING);
        this.seekOnPrepared = 0; //reset only when played
    } else {
        this.setState(STATE.MEDIA_STARTING);
    }
    // Save off duration
    this.duration = getDurationInSeconds();
    // reset prepare only flag
    this.prepareOnly = true;

    // Send status notification to JavaScript
    sendStatusChange(MEDIA_DURATION, null, this.duration);
}

输出

Column_ID    Column_Name
123          (3862,3654,3828)

PL / SQL代码

Column_ID    Column_Name
123          3862
123          3654
123          3828