Parse varchar2 to table (Oracle)

2019-09-06 17:20发布

问题:

Is there built-in function in Oracle DB 11g r2 that could parse varchar2 variable to table? Opposite of listagg or wm_concat. I found only Tom Kyte's method dated 2006:

with data as
(
select trim(substr (txt, instr(txt, ',', 1, level) + 1
       , instr(txt, ',', 1, level + 1) - instr(txt, ',', 1, level) - 1)) as token
from (select ',' || :txt || ',' txt from dual)
connect by level <= length(:txt) - length(replace(:txt, ',', '')) + 1
)
select * from data;

I think Oracle must have simpler way.

回答1:

No.

I would simplify Tom's method slightly, but not by much; you can now use regular expressions as well:

select regexp_substr(:txt, '[^,]+', 1, level)
   from dual
 connect by regexp_substr(:txt, '[^,]+', 1, level) is not null

SQL Fiddle



回答2:

Ben's regexp_substr solution is generally the preferred solution. If your string happens to consist of strings that are valid Oracle identifiers-- they are less than or equal to 30 characters and begin with an alphabetic character, you can also use the dbms_utility.comma_to_table function. Given those limitations, however, it's generally better to use the general-purpose solution.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    l_string varchar2(1000) := 'foo,bar,b123,FuzzyBunny,abcdefghij12345678901234567890';
  3    l_num    pls_integer;
  4    l_arr    dbms_utility.uncl_array;
  5  begin
  6    dbms_utility.comma_to_table( l_string, l_num, l_arr );
  7    for i in 1..l_arr.count
  8    loop
  9      dbms_output.put_line( l_arr(i) );
 10    end loop;
 11* end;
SQL> /
foo
bar
b123
FuzzyBunny
abcdefghij12345678901234567890

PL/SQL procedure successfully completed.