Convert comma separated string to array in PL/SQL

前端 未结 14 2173
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 03:19

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.

相关标签:
14条回答
  • 2020-11-27 03:59
    declare
    seprator varchar2(1):=',';
    dosweeklist varchar2(4000):='a,b,c';
    begin
    for i in (SELECT  SUBSTR(dosweeklist,
                             case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end,
                             NVL(NULLIF(INSTR(dosweeklist,seprator,1,LEVEL),0),length(dosweeklist)+1) - case when level=1 then 1 else INSTR(dosweeklist,seprator,1,LEVEL-1)+1 end) dat 
              FROM dual
              CONNECT BY LEVEL <= LENGTH(dosweeklist) - LENGTH(REPLACE(dosweeklist,seprator,'')) +1)
    loop
    dbms_output.put_line(i.dat);
    end loop;
    end;
    /
    

    so select query only in for loop can do the trick, by replacing dosweeklist as your delimited string and seprator as your delimited character.

    Lets see output

    a
    
    b
    
    c
    
    0 讨论(0)
  • 2020-11-27 04:00

    We can never run out of alternatives of doing the same thing differently, right? I recently found this is pretty handy:

    DECLARE
       BAR   VARCHAR2 (200) := '1,2,3';
    BEGIN
       FOR FOO IN (    SELECT REGEXP_SUBSTR (BAR,
                                             '[^,]+',
                                             1,
                                             LEVEL)
                                 TXT
                         FROM DUAL
                   CONNECT BY REGEXP_SUBSTR (BAR,
                                             '[^,]+',
                                             1,
                                             LEVEL)
                                 IS NOT NULL)
       LOOP
          DBMS_OUTPUT.PUT_LINE (FOO.TXT);
       END LOOP;
    END;
    

    Outputs:

    1
    2
    3
    
    0 讨论(0)
提交回复
热议问题