How to get through delimited list in Oracle PLSQL

I am working on an Oracle procedure that calls another procedure in it. One of my options (parm1)may contain one or more values ​​in a comma-separated list. How can I iterate over these values ​​to pass them one by one to another procedure?

Here is an example of what I would like to do:

When Parm1 = 123,312

callProcedure2(123)
callProcedure2(321)

-or -

When Parm1 123

callProcedure2(123)

I think this can be done with a loop, but I cannot figure out how to get it to use each value as a dedicated call in the loop.

Any help would be appreciated!

Thank!

+3
source share
3 answers

Just iterate over the substrings:

declare 
  parm1 varchar2(1000) := '123,234,345,456,567,789,890';

  vStartIdx binary_integer;
  vEndIdx   binary_integer;
  vCurValue varchar2(1000);
begin

  vStartIdx := 0;
  vEndIdx   := instr(parm1, ','); 

  while(vEndIdx > 0) loop
    vCurValue := substr(parm1, vStartIdx+1, vEndIdx - vStartIdx - 1);

    -- call proc here
    dbms_output.put_line('->'||vCurValue||'<-');

    vStartIdx := vEndIdx;
    vEndIdx := instr(parm1, ',', vStartIdx + 1);  
  end loop;

  -- Call proc here for last part (or in case of single element)
  vCurValue := substr(parm1, vStartIdx+1);
  dbms_output.put_line('->'||vCurValue||'<-');

end;
+7
source
CURSOR V_CUR IS
select regexp_substr(Parm1 ,'[^,]+', 1, level) As str from dual
connect by regexp_substr(Parm1, '[^,]+', 1, level) is not null;

,

123
321

.

For i IN V_CUR
LOOP
    callProdcedure2(i.str);
END LOOP;
+12

You can use a function that you can use in a loop for(without regexpfor ThinkJet):

Create type and function

CREATE OR REPLACE TYPE t_my_list AS TABLE OF VARCHAR2(100);
CREATE OR REPLACE
       FUNCTION cto_table(p_sep in Varchar2, p_list IN VARCHAR2)
         RETURN t_my_list
       AS
         l_string VARCHAR2(32767) := p_list || p_sep;
         l_sep_index PLS_INTEGER;
         l_index PLS_INTEGER := 1;
         l_tab t_my_list     := t_my_list();
       BEGIN
         LOOP
           l_sep_index := INSTR(l_string, p_sep, l_index);
           EXIT
         WHEN l_sep_index = 0;
           l_tab.EXTEND;
           l_tab(l_tab.COUNT) := TRIM(SUBSTR(l_string,l_index,l_sep_index - l_index));
           l_index            := l_sep_index + 1;
         END LOOP;
         RETURN l_tab;
       END cto_table;
/

Then, how to call it in a for loop:

DECLARE
  parm1 varchar2(4000) := '123,234,345,456,567,789,890';
BEGIN
    FOR x IN (select * from (table(cto_table(',', parm1)) ) )
    LOOP
        dbms_output.put_line('callProdcedure2 called with ' || x.COLUMN_VALUE);
        callProdcedure2(x.COLUMN_VALUE);
    END LOOP;
END;
/

Note the default name COLUMN_VALUEgiven by Oracle, which is required for use, which I want to make from the result.

The result, as expected:

callProdcedure2 called with 123
callProdcedure2 called with 234
...
0
source

All Articles