select from comma-separated list
July 3rd, 2009
This is asked over and over in the forums, but why not proposing an 11g solution here
create table t(description varchar2(12) primary key,
numbers varchar2(4000));
insert into t(description, numbers) values ('PRIME','2,3,5,7');
insert into t(description, numbers) values ('ODD','1,3,5,7,9');
commit;
| DESCRIPTION | NUMBERS |
|---|---|
| PRIME | 2,3,5,7 |
| ODD | 1,3,5,7,9 |
Now I want to unpivot numbers in rows
select description,(column_value).getnumberval()
from t,xmltable(numbers)
| DESCRIPTION | (COLUMN_VALUE).GETNUMBERVAL() |
|---|---|
| PRIME | 2 |
| PRIME | 3 |
| PRIME | 5 |
| PRIME | 7 |
| ODD | 1 |
| ODD | 3 |
| ODD | 5 |
| ODD | 7 |
| ODD | 9 |
It is that simple
Works also with strings :
select (column_value).getstringval()
from xmltable('"a","b","c"');
| (COLUMN_VALUE).GETSTRINGVAL() |
|---|
| a |
| b |
| c |
with strings it is more challenging if you want to deal with empty strings, entity escaping, etc…
Nice
Didn’t realize that “column_value” could be used beyond the scope of xmldb. Thanks.
M.
Although I knew that you mimic it in 9i via
select value(Z) AS object_value from MY_TABLE Z;
This is an elegant solution in 11g, but how would you do this in Oracle 9i?
Thanks!
I would create a plsql function
It should perform better
xmltable is a 10gR2 function, but only in 11g it accepts dynamic programming