How can I select from list of values in Oracle

前端 未结 6 2116
刺人心
刺人心 2020-11-28 02:28

I am referring to this stackoverflow answer:

How can I select from list of values in SQL Server

How could something similar be done in O

6条回答
  •  有刺的猬
    2020-11-28 03:07

    There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL

    SQL> ed
    Wrote file afiedt.buf
    
      1  with x as (
      2    select '1,2,3,a,b,c,d' str from dual
      3  )
      4   select regexp_substr(str,'[^,]+',1,level) element
      5     from x
      6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
    SQL> /
    
    ELEMENT
    ----------------------------------------------------
    1
    2
    3
    a
    b
    c
    d
    
    7 rows selected.
    

    Or in PL/SQL

    SQL> create type str_tbl is table of varchar2(100);
      2  /
    
    Type created.
    
    SQL> create or replace function parse_list( p_list in varchar2 )
      2    return str_tbl
      3    pipelined
      4  is
      5  begin
      6    for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
      7                from dual
      8             connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
      9    loop
     10      pipe row( x.element );
     11    end loop
     12    return;
     13  end;
     14
     15  /
    
    Function created.
    
    SQL> select *
      2    from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));
    
    COLUMN_VALUE
    --------------------------------------------------------------------------------
    a
    b
    c
    1
    2
    3
    d
    e
    f
    
    9 rows selected.
    

提交回复
热议问题