Monday, August 4, 2008

Regular Expression: How to split comma seperated values using sql

Lets create a table first and insert few comma seperated rows.

1) create table tab1 (owner number, cars varchar2(200));

2) insert into tab1 (
select 1, 'Ford,Toyota,Nissan' from dual union all
select 2, 'Lexus,Mercedes,BMW,Infiniti' from dual union all
select 3, 'Ferrari' from dual union all
select 4, 'Porsche,Lotus,Lamborghini,Maserati,Aston Martin' from dual union all
select 5, 'Maybach,Bentley' from dual);

3) select owner, cars str from tab1;

Now here is the sql to split.

select owner, car
from ( select owner, regexp_substr(str, '[^,]+', 1, level) car,
level lv
, lag(level, 1, 0) over (partition by owner order by level) lg
from ( select owner, cars str from tab1 )
connect by regexp_substr(str, '[^,]+', 1, level) is not null
)
where lv != lg;

Replace"," in
[^,] with your delimiter

No comments:

Post a Comment