How to convert comma separated values to rows in oracle?

前端 未结 4 1348
死守一世寂寞
死守一世寂寞 2020-11-22 07:55

Here is the DDL --

create table tbl1 (
   id number,
   value varchar2(50)
);

insert into tbl1 values (1, \'AA, UT, BT, SK, SX\');
insert into tbl1 values (         


        
4条回答
  •  粉色の甜心
    2020-11-22 08:08

    This will get the values without requiring you to remove duplicates or having to use a hack of including SYS_GUID() or DBMS_RANDOM.VALUE() in the CONNECT BY:

    SELECT t.id,
           v.COLUMN_VALUE AS value
    FROM   TBL1 t,
           TABLE(
             CAST(
               MULTISET(
                 SELECT TRIM( REGEXP_SUBSTR( t.value, '[^,]+', 1, LEVEL ) )
                 FROM   DUAL
                 CONNECT BY LEVEL <= REGEXP_COUNT( t.value, '[^,]+' )
               )
               AS SYS.ODCIVARCHAR2LIST
             )
           ) v
    

    Update:

    Returning the index of the element in the list:

    Option 1 - Return a UDT:

    CREATE TYPE string_pair IS OBJECT( lvl INT, value VARCHAR2(4000) );
    /
    
    CREATE TYPE string_pair_table IS TABLE OF string_pair;
    /
    
    SELECT t.id,
           v.*
    FROM   TBL1 t,
           TABLE(
             CAST(
               MULTISET(
                 SELECT string_pair( level, TRIM( REGEXP_SUBSTR( t.value, '[^,]+', 1, LEVEL ) ) )
                 FROM   DUAL
                 CONNECT BY LEVEL <= REGEXP_COUNT( t.value, '[^,]+' )
               )
               AS string_pair_table
             )
           ) v;
    

    Option 2 - Use ROW_NUMBER():

    SELECT t.id,
           v.COLUMN_VALUE AS value,
           ROW_NUMBER() OVER ( PARTITION BY id ORDER BY ROWNUM ) AS lvl
    FROM   TBL1 t,
           TABLE(
             CAST(
               MULTISET(
                 SELECT TRIM( REGEXP_SUBSTR( t.value, '[^,]+', 1, LEVEL ) )
                 FROM   DUAL
                 CONNECT BY LEVEL <= REGEXP_COUNT( t.value, '[^,]+' )
               )
               AS SYS.ODCIVARCHAR2LIST
             )
           ) v;
    

提交回复
热议问题