Oracle递归SELECT

时间:2013-10-03 14:04:00

标签: oracle select recursive-query

以下是我要解决的问题(Oracle v10g +) 表1数据:

ID        Text_Formula    
1         'FIELD1 = XYZ + ABC'

表2数据:

ID       Formula_Component      Actual_Component    
1              XYZ                  a.br_width    
1              ABC                  b.br_height

期望的结果:

ID       Text_Formula    
1        'FIELD1 = a.br_width + b.br_height'

表2可以包含任意数量的行。我尝试过将LEAD,LAG,xmlagg与REPLACE结合使用的变体,并没有找到任何有效的东西。任何指针都将非常感谢!

2 个答案:

答案 0 :(得分:0)

我认为你应该为这个操作创建一个函数,并在table1的select查询中使用这个函数,函数应该是这样的;

create or replace function transform_data(p_input in varchar2) return varchar2
is
    v_result varchar2(2000);
    v_col_value varchar2(200);
begin
    v_result := p_input;

    for rec in (select * from table2)
    loop
        if instr(v_result, rec.Formula_Component) > 0 then
            v_result := replace(v_result, rec.Formula_Component, rec.Actual_Component);
        end if;
    end loop;

    return v_result;
end;

答案 1 :(得分:0)

select id, replace(formula, chr(0)) as text_formula from (
  select 
    id, rn, regexp_replace(text_formula, '(\w+)', chr(0)||'\1'||chr(0)) formula
  from t1 natural join (select id, count(0) rn from t2 group by id)
) model 
reference dic on (
  select 
    id, 
    chr(0)||formula_component||chr(0) as term, 
    actual_component as value,
    row_number() over (partition by id order by null) as rn
  from t2
) dimension by (id, rn) measures (term, value)
partition by (id) dimension by (1 x) measures (formula, rn)
rules iterate (1000000) until (rn[1] <= 0) (
  formula[1] = replace(formula[1], term[cv(id), rn[1]], value[cv(id), rn[1]]),
  rn[1] = rn[1] - 1
)

fiddle