Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert comma separated string to array in PL/SQL

How do I convert a comma separated string to a array?

I have the input '1,2,3' , and I need to convert it into an array.

like image 687
Suvonkar Avatar asked Sep 29 '10 06:09

Suvonkar


People also ask

How to convert string into rows in Oracle?

A delimiter-separated string can be converted to a set of rows in Oracle SQL, with the combination of the regex function REGEX_SUBSTR and recursion via CONNECT BY. This feature can be used for splitting a single input string with comma-separated query parameters, into a list of values.

How do you split comma-separated string and pass to in clause of select statement in Oracle?

You need to combine two nested statement: Select * From Employee Emp Where Emp. Emp_Name In (Select Regexp_Substr('KING,JONES,FORD' ,'[^,]+' ,1 ,Level) Emp_Name From Dual Connect By Regexp_Substr('KING,JONES,FORD' ,'[^,]+' ,1 ,Level) Is Not Null);


2 Answers

Oracle provides the builtin function DBMS_UTILITY.COMMA_TO_TABLE.

Unfortunately, this one doesn't work with numbers:

SQL> declare   2    l_input varchar2(4000) := '1,2,3';   3    l_count binary_integer;   4    l_array dbms_utility.lname_array;   5  begin   6    dbms_utility.comma_to_table   7    ( list   => l_input   8    , tablen => l_count   9    , tab    => l_array  10    );  11    dbms_output.put_line(l_count);  12    for i in 1 .. l_count  13    loop  14      dbms_output.put_line  15      ( 'Element ' || to_char(i) ||  16        ' of array contains: ' ||  17        l_array(i)  18      );  19    end loop;  20  end;  21  / declare * ERROR at line 1: ORA-00931: missing identifier ORA-06512: at "SYS.DBMS_UTILITY", line 132 ORA-06512: at "SYS.DBMS_UTILITY", line 164 ORA-06512: at "SYS.DBMS_UTILITY", line 218 ORA-06512: at line 6 

But with a little trick to prefix the elements with an 'x', it works:

SQL> declare   2    l_input varchar2(4000) := '1,2,3';   3    l_count binary_integer;   4    l_array dbms_utility.lname_array;   5  begin   6    dbms_utility.comma_to_table   7    ( list   => regexp_replace(l_input,'(^|,)','\1x')   8    , tablen => l_count   9    , tab    => l_array  10    );  11    dbms_output.put_line(l_count);  12    for i in 1 .. l_count  13    loop  14      dbms_output.put_line  15      ( 'Element ' || to_char(i) ||  16        ' of array contains: ' ||  17        substr(l_array(i),2)  18      );  19    end loop;  20  end;  21  / 3 Element 1 of array contains: 1 Element 2 of array contains: 2 Element 3 of array contains: 3  PL/SQL procedure successfully completed. 

Regards, Rob.

like image 30
Rob van Wijk Avatar answered Sep 24 '22 19:09

Rob van Wijk


here is another easier option

select to_number(column_value) as IDs from xmltable('1,2,3,4,5'); 
like image 188
Richard Sylvester Avatar answered Sep 21 '22 19:09

Richard Sylvester