Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse comma delimited string in PL/SQL? [duplicate]

I have a comma delimited string in a PL/SQL script (e.g. data:= 'a,b,c,d,e'), that I need to parse out within the script.

I would like to loop through the string and process each item. Like a 'foreach' loop.

Is this possible in PL/SQL? Can someone point me to some code?

like image 844
TERACytE Avatar asked Aug 11 '11 14:08

TERACytE


People also ask

How do you remove duplicates from a comma separated string in SQL?

Solution 1 -- Sort the values: SELECT value FROM STRING_SPLIT(@temp, ',') ORDER BY value; -- Remove duplicates: SELECT DISTINCT value FROM STRING_SPLIT(@temp, ',');

How Split comma separated string and pass to in clause of select statement?

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);

How convert comma separated values into columns in Oracle?

You can use regexp_substr() : select regexp_substr(val, '[^,]+', 1, 1) as val1, regexp_substr(val, '[^,]+', 1, 2) as val2, regexp_substr(val, '[^,]+', 1, 3) as val3, . . . I would suggest that you generate a column of 255 numbers in Excel (or another spreadsheet), and use the spreadsheet to generate the SQL code.


2 Answers

If you are on Oracle 10G or 11G then you should have a built-in Apex function apex_util.string_to_table:

SQL> declare
  2    v_array apex_application_global.vc_arr2;
  3    v_string varchar2(2000);
  4  begin
  5  
  6    -- Convert delimited string to array
  7    v_array := apex_util.string_to_table('alpha,beta,gamma,delta', ',');
  8    for i in 1..v_array.count
  9    loop
 10      dbms_output.put_line(v_array(i));
 11    end loop;
 12  
 13    -- Convert array to delimited string
 14    v_string := apex_util.table_to_string(v_array,'|');
 15    dbms_output.put_line(v_string);
 16  end;
 17  /
alpha
beta
gamma
delta
alpha|beta|gamma|delta

PL/SQL procedure successfully completed.
like image 171
Tony Andrews Avatar answered Sep 28 '22 03:09

Tony Andrews


Oracle 11g:

SELECT   num_value
  FROM   (    SELECT   TRIM (REGEXP_SUBSTR (num_csv,
                                            '[^,]+',
                                            1,
                                            LEVEL))
                          num_value
                FROM   (    SELECT   '1,2,3,4,5,6,7,8,9,10' num_csv FROM DUAL)
          CONNECT BY   LEVEL <= regexp_count (num_csv, ',', 1) + 1)
 WHERE   num_value IS NOT NULL
like image 27
Julfcar Ali Avatar answered Sep 28 '22 03:09

Julfcar Ali