的Oracle SQL分割字符串行

问题描述:

我有字符串“ABC”我需要分成数行如下的Oracle SQL分割字符串行

A 
B 
C 

。我知道怎么做的时候分隔符是存在的。如何当分隔符不存在

with test as 
(select 'A,B,C' col1 from dual) 
    select regexp_substr(col1, '[^,]+', 1, rownum) result1 
    from test 
    connect by level <= length(regexp_replace(col1, '[^,]+')) + 1; 
+0

它是否总是3个字符在每个之后用逗号分隔? – sagi

+0

没有。它是可变的。 –

无定界符应该是更容易 - 使用同样的方法,但只是使用substrlevel为字符串的索引:

with test as 
(select 'ABC' col1 from dual) 
    select substr(col1, level, 1) result1 
    from test 
    connect by level <= length(col1); 
+0

虽然它在行中工作,但它不适用于多行 –

你可以使用类似这样的功能

-- define type 
CREATE OR REPLACE TYPE TABLE_OF_STRING AS TABLE OF VARCHAR2(32767); 

-- function 
function SPLIT_STRING_TO_STRINGS 
    (
    p_list varchar2, 
    p_delimiter varchar2 := ',' 
) return TABLE_OF_STRING pipelined 
    is 
    l_idx pls_integer; 
    l_list varchar2(32767) := p_list; 
    begin 
    loop 
     l_idx := instr(l_list, p_delimiter); 
     if l_idx > 0 then 
      pipe row(substr(l_list, 1, l_idx-1)); 
      l_list := substr(l_list, l_idx + length(p_delimiter)); 
     else 
      pipe row(l_list); 
      exit; 
     end if; 
    end loop; 
    return; 
    end SPLIT_STRING_TO_STRINGS; 

-- usage example 
select * from table(SPLIT_STRING_TO_STRINGS('A,B,C',','))