Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

sql - Splitting comma separated values in Oracle

I have column in my database where the values are coming like the following:

3862,3654,3828

In dummy column any no. of comma separated values can come. I tried with following query but it is creating duplicate results.

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

I am not understanding the problem. Can anyone can help?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Works perfectly for me -

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>

There are many other ways of achieving it. Read Split single comma delimited string into rows.

Update Regarding the duplicates when the column is used instead of a single string value. Saw the use of DBMS_RANDOM in the PRIOR clause to get rid of the cyclic loop here

Try the following,

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>

Update 2

Another way,

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...