Oracle Dividir texto en columnas

I searched the forum, but I couldn't get the answer I was looking for.

I have a long varchar2 in my database. I need to split this by |.

Example: HEADER|20140528|3407

So, I wrote a query like this:

select regexp_substr(datas,'[^|]+',1,1) as col_1, 
       regexp_substr(datas,'[^|]+',1,2) as col_2,
       regexp_substr(datas,'[^|]+',1,3) as col_3
from temp_gerben

However, it could be that the second value is blank. In that case, the line looks like: HEADER||3407

But the same query doesn't handle this so well. It is simple ignoring the second field, and puts the third field in it's place.

As I need this data split for different reports, I need it to keep that field empty instead of ignoring.

preguntado el 28 de mayo de 14 a las 12:05

1 Respuestas

The problem is that your regular expression is looking for at least one non-| character, and there is none in your expression. One way to fix this is to add such a character:

select regexp_substr(replace(datas, '||', '| |'), '[^|]+', 1, 1) as col_1, 
       regexp_substr(replace(datas, '||', '| |'), '[^|]+', 1, 2) as col_2,
       regexp_substr(replace(datas, '||', '| |'), '[^|]+', 1, 3) as col_3
from (select 'HEADER|20140528|3407' as datas from dual union all
      select 'HEADER||3407' from dual
     ) temp_gerben;

Another way is to search for the delimiting character, using * en lugar de +. That doesn't quite work, because the counting gets off. You can make it work by appening a | to the end of the string, looking for the patter than ends with |, and then removing the |:

select replace(regexp_substr(datas || '|', '[^|]*[|]', 1, 1), '|', '') as col_1, 
       replace(regexp_substr(datas || '|', '[^|]*[|]', 1, 2), '|', '') as col_2,
       replace(regexp_substr(datas || '|', '[^|]*[|]', 1, 3), '|', '') as col_3
from (select 'HEADER|20140528|3407' as datas from dual union all
      select 'HEADER||3407' from dual
     ) temp_gerben;

contestado el 28 de mayo de 14 a las 13:05

Thank a lot. I ended up using your first solution. I am using this in a procedure, so I am simply replacing the ' ' value with a null value. - Gerben

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.