1

I have a string in Oracle database, my string is: 'bbb;aaa;qqq;ccc'

I used regexp for split my string:

select distinct trim(regexp_substr('bbb;aaa;qqq;ccc','[^;]+', 1,level) ) as q 
from dual
connect by regexp_substr('bbb;aaa;qqq;ccc', '[^;]+', 1, level) is not null ;

I want to split it in order, I expected the below output always:

bbb
aaa
qqq
ccc

because order of the subString are very important for me. but the result of this query is not in order:

qqq
aaa
bbb
ccc

2 Answers 2

5

You don't need a DISTINCT to get your result; besides, to get the result in a given order, all you need is an ORDER BY clause:

select trim(regexp_substr('bbb;aaa;qqq;ccc','[^;]+', 1,level) ) as q 
from dual
connect by regexp_substr('bbb;aaa;qqq;ccc', '[^;]+', 1, level) is not null
order by level
Sign up to request clarification or add additional context in comments.

Comments

2

If you do need DISTINCT:

WITH your_data( value ) AS (
  SELECT 'bbb;aaa;qqq;ccc;aaa;eee' FROM DUAL
),
positions ( string, lvl, start_pos, end_pos ) AS (
  SELECT value, 1, 1, INSTR( value, ';', 1, 1 ) FROM your_data
UNION ALL
  SELECT string, lvl + 1, end_pos + 1, INSTR( string, ';', 1, lvl + 1 )
  FROM positions
  WHERE  end_pos > 0
),
substrings ( string, substring, lvl, start_pos ) AS (
  SELECT string,
         DECODE( end_pos, 0, SUBSTR( string, start_pos ), SUBSTR( string, start_pos, end_pos - start_pos ) ),
         lvl,
         start_pos
  FROM   positions
)
SELECT string,
       substring,
       lvl
FROM   substrings
WHERE  INSTR( ';' || string || ';', ';' || substring || ';' ) = start_pos;

Output:

STRING                  SUBSTRING                      LVL
----------------------- ----------------------- ----------
bbb;aaa;qqq;ccc;aaa;eee bbb                              1
bbb;aaa;qqq;ccc;aaa;eee aaa                              2
bbb;aaa;qqq;ccc;aaa;eee qqq                              3
bbb;aaa;qqq;ccc;aaa;eee ccc                              4
bbb;aaa;qqq;ccc;aaa;eee eee                              6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.