Oracle - Merge中的子查询减少

时间:2016-09-29 13:53:59

标签: sql oracle merge oracle11gr2

我的MERGEsubquery来获取和ID,我想知道subquery in the NOT MATCHED statement是否总是被执行。

        MERGE INTO CAR_STOCK st
        USING CAR_PRODUCTO pro
        ON (pro.id = st.producto_id AND pro.ean = ?)
        WHEN MATCHED THEN
        UPDATE SET st.stockActual = ?
        WHEN NOT MATCHED THEN
        INSERT (stockActual, local_id, producto_id, activo)
        VALUES (?, ?, (SELECT id FROM car_producto WHERE ean = ?), 'S');

谢谢!

编辑: ?是因为我在JDBC中使用PreparedStatement

1 个答案:

答案 0 :(得分:1)

不需要子查询,您只需引用pro.id部分中的insert,就像这里:

merge into t1 using t2 on (t1.a = t2.a)
  when matched then update set t1.b = t2.b
  when not matched then insert (a, b)
  values (0, t2.b)

测试数据和merge结果:

create table t1 as (select 1 a, 'a01' b from dual);
create table t2 as (select 1 a, 'a05' b from dual union all select 2 a, 'bxx' b from dual );

     A  B
------  ---
     1  a05
     0  bxx