Split string using pl/sql using connect level on null value

℡╲_俬逩灬. 提交于 2019-12-06 01:57:35

you can combine INSTR und SUBSTR to achive the desiered result:

select  
  str, 
  replace(substr(str, 
                 case level 
                 when 1 then 0 
                 else instr( str, '~',1, level-1) 
                 end 
                  +1,
                 1
                ), '~')
from ( select 'A~B~C~D~E' as str from dual)
connect by level <= length(regexp_replace(str,'[^~]+')) + 1
;

You can use NULLS FIRST in the ORDER BY clause

select regexp_substr('~B~C','[^~]+',1,level) output
from dual
connect by level <= length(regexp_replace('~B~C','[^~]+')) + 1
ORDER BY regexp_substr('~B~C','[^~]+',1,level) NULLS FIRST;

To quote from Oracle documentation

If the null ordering is not specified then the handling of the null values is:

NULLS LAST if the sort is ASC

NULLS FIRST if the sort is DESC

If neither ascending nor descending order is specified, and the null ordering is also not specified, then both defaults are used and thus the order will be ascending with NULLS LAST.

Because I used single characters as example in my question, but in practicality I'm using long strings in my project, for example 'How~do~I~do~this'

I came across this solution from OTN Oracle.com, thanks to chris227.

SELECT CAST(REGEXP_SUBSTR (str, '(.*?)(~|$)', 1, level, null, 1) AS CHAR(12))  output
FROM (select 'How~do~I~do~this' as str from dual)
CONNECT BY level <= regexp_count(str, '~') + 1;

This will work even with single characters.

Hope this will help others looking for similair solutions.

antoniolvsa

I know that it is late now, but I think that what you (and I) needed was this:

select REPLACE(regexp_substr('A~~C','[^~]*(~)?',1,level),'~') output, level
from dual
connect by level <= length(regexp_replace('A~~C','[^~]+')) + 1
ORDER BY level;

Since this problem was fresh on my mind and I happened to see this post, I respectfully submit my suggestion which builds on user3767503's answer. It reduces the number of function calls needed. It uses some 11g updates to regexp_substr() and makes use of regexp_count() which I believe was also introduced in 11g. It assumes the number of fields is the number of delimiters plus one.

select regexp_substr('AAA~X~C~~DD~~~E', '([^~]*)(~|$)', 1, level, null, 1) output, level
from dual
connect by level <= regexp_count('AAA~X~C~~DD~~~E','~') + 1 
ORDER BY level;

See this post for more info and detail on reading the regex pattern: Split comma seperated values to columns.

The bottom line is the commonly used regex pattern of '[^<delimiter>]+' to parse a string fails when there is a null in the list and should be avoided, IMHO.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!