How to loop through a delimited list in Oracle PLSQL

后端 未结 4 1189
青春惊慌失措
青春惊慌失措 2021-01-01 05:40

I am working on an Oracle procedure that calls another procedure within it. One of my parameters (parm1) can contain one or more values in a comma separated lis

4条回答
  •  执念已碎
    2021-01-01 06:19

    It is possible to use a function that you can use in a for loop (without regexp for ThinkJet):

    Create a 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 the 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;
    /
    

    Notice the default name COLUMN_VALUE given by Oracle, which is necessary for the use I want to make of the result.

    Result as expected:

    callProdcedure2 called with 123
    callProdcedure2 called with 234
    ...
    

提交回复
热议问题