简体   繁体   中英

How to split comma delimited list of strings in oracle plsql, when the individual string itself is having comma in it?

Table T1

C1   |  C2
-----+------
A,B  |  C,D

Code:

DECLARE
    l_varchar VARCHAR2(100);
BEGIN
    SELECT C1||','||C2 INTO l_varchar FROM T1;
END;

Now I need to split values in l_varchar based on COMMA delimiter.

If I try to split as given in http://sqlfiddle.com/#!4/b42db/7

I get:

A
B
C
D

But I need:

A,B
C,D

Can you please help me to get this desired output.

Can I do something while concatenating the strings, so that later I will be able to split it?

Below query is used to concatenate, can this be tweaked?

SELECT C1||','||C2 INTO l_varchar FROM T1;

Query used to split comma delimited string:

select 
    regexp_substr(C1||','||c2 ,'[^,]+', 1, level) As str 
from 
    (select 'A,B' c1, 'C,D' c2 from dual)
CONNECT BY LEVEL <= regexp_count(C1||','||c2, ',') + 1

Unless I am misunderstanding, what you are trying to do is not possible unless you use a different delimiter. Example :

SELECT C1||';'||C2 INTO l_varchar FROM T1;

here is a very nice and correct way to do it:

SELECT *
FROM   t1
UNPIVOT (unpivoted_column FOR original_column 
         IN (c1 AS 'C1', c2 AS 'C2'));

For any further clarifications don't hesitate to ask me.

Ted.

Best possible way is to use the REGEXP combinations. Hope the below snippet helps you to get the desired result.

SELECT regexp_substr(a.c, '[^*]+', 1, level) TXT
FROM
  (SELECT COL1
    ||'*'
    ||COL2
    ||'*'
    ||COL3 C
  FROM
    (SELECT 'A,B' COL1,'C,D' COL2,'E,F' COL3 FROM DUAL
    )
  )A
  CONNECT BY LEVEL <= LENGTH(A.C)-LENGTH(REPLACE(A.C,'*',''))+1; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM