Oracle复杂字符串替换

时间:2013-02-08 21:16:15

标签: sql oracle plsql oracle10g

我有下表

mytable 
type         | id       | name           | formula  
"simple"     | 1        | "COUNT"        | "<1>"  
"simple"     | 2        | "DISTINCT"     | "<2>"  
"simple"     | 3        | "mycol"        | "<3>"  
"complex"    | 4        | null           | "<1>(<2> <3>)"  

现在我想阅读此表并添加一个替换公式字符串的附加列。 对于id 4,我需要:"COUNT(DISTINCT mycol)"
知道我该怎么做吗?

1 个答案:

答案 0 :(得分:1)

在Oracle 11中,它可能如下所示:

select
   type, id, name, formula, value
from 
   mytable
   left join (
      select
         id_complex,
         listagg(decode(pos, 2, name, part)) within group (order by occ, pos) as value
      from 
         (
            select
               id_complex, occ, pos,
               regexp_replace(pair, '^(.*?)(<.*?>)$', '\'||pos) as part
            from
               (
                  select
                     id as id_complex,
                     occ,
                     regexp_substr(formula||'<>', '.*?<.*?>', 1, occ) as pair
                  from
                     (
                        select level as occ from dual
                        connect by level <= (select max(length(formula)) from mytable)
                     ),
                     mytable
                  where type = 'complex'
               ),
               (select level as pos from dual connect by level <= 2)
         )
         left join mytable on part = formula and type = 'simple'
      group by id_complex
   ) on id = id_complex
order by id

SQL Fiddle