Split comma separated values to columns in Oracle

后端 未结 4 1648
温柔的废话
温柔的废话 2020-11-22 01:58

I have values being returned with 255 comma separated values. Is there an easy way to split those into columns without having 255 substr?

ROW  | VAL
--------         


        
4条回答
  •  自闭症患者
    2020-11-22 02:25

    If you only have one row, and time to create your

    • create your own built-in cto_table function to split a string on any separator, then you can use PIVOT + LISTAGG to do it like follows:

    select * from (
      select rownum r , collection.*  
        from TABLE(cto_table(',','1.25, 3.87, 2, 19,, 1, 9, ')) collection
    )
    PIVOT ( 
      LISTAGG(column_value) within group (order by 1) as val 
      for r in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
    )
    

    FYI: here is how to create the cto_table 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;
    /
    

提交回复
热议问题