2016-01-13 95 views
1

我有字符串「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

沒有。它是可變的。 –

回答

4

無定界符應該是更容易 - 使用同樣的方法,但只是使用substrlevel爲字符串的索引:

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

雖然它在行中工作,但它不適用於多行 –

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',','))