Search code examples
oracle-databasecsvsizevarray

How to insert the comma separated value in table


I have a table like that:

columnId1 => "word1,word2,word3"
columnId3 => "word4,word5,word6"

I want to create a table like that:

columnId1  word1
columnId1  word2
columnId1  word3
columnId2  word4
columnId2  word5
columnId2  word6

How can I do it in PLSQL?


Solution

  • create table testtable(col1 varchar2(50) , col2 varchar2(50));
    
    insert into testtable (col1, col2)
    with commadata as(
    select 'word1,word2,word3' columnid1, 'word4,word5,word6' columnid2
      from dual
      )
    select       regexp_substr( columnid1 
                              , '[^,]+'
                              ,1
                              ,level)    as parsed_value
                              ,
    regexp_substr( columnid2 
                              , '[^,]+'
                              ,1
                              ,level)    as parsed_value                          
    
      from commadata
    connect by level  <= REGEXP_COUNT( columnid1 , '[,]' )+1    
    ;  
    select * from testtable;  
    
    COL1                                               COL2                                               
    -------------------------------------------------- -------------------------------------------------- 
    word1                                              word4                                              
    word2                                              word5                                              
    word3                                              word6   
    

    this is assuming you are using 10g and have access to Regular Expressions. this should give you enough to go on to create your statements, do note it is brittle and can break if columnId1 and columnId2 have different amounts of commas and such.