【问题标题】:Oracle recursive SELECTOracle 递归选择
【发布时间】:2013-10-03 14:04:00
【问题描述】:

这是我要解决的问题 (Oracle v10g+)。
表一数据:

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 的变体,但没有找到任何可行的方法。任何指针将不胜感激!

【问题讨论】:

标签: oracle select recursive-query


【解决方案1】:

我认为你应该为这个操作创建一个函数,并在你从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;

【讨论】:

  • 谢谢 - 这可以解决问题。我将自己交给一个函数,虽然我更喜欢 sql。鉴于少量数据,函数应该不是问题。再次感谢!
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-17
    • 2018-12-31
    • 1970-01-01
    • 2015-02-13
    • 2023-03-29
    相关资源
    最近更新 更多