在 Oracle 中,您可以对(某些)视图或子查询执行 DML。指导原则是,如果 Oracle 能够从视图中检索物理行,则视图是可更新的。
因此,您可以在子查询上使用MERGE 。在某些情况下这是有道理的。例如,假设您有一个带有状态列的表。您想将新信息合并到此表中,但只修改具有STATUS='active'
. 你可以写:
MERGE INTO (SELECT * FROM mytable WHERE status='active') old
USING (SELECT * FROM newtable) new
ON (new.id = old.id)
WHEN MATCHED THEN UPDATE SET old.data1=new.data1;
编辑
看来这会ORA-00903
在 9iR2 中产生。不过它适用于 11g。测试脚本:
create table t (id number, c varchar2(10));
insert into t (select rownum, 'aaa' from dual connect by level <= 1000);
merge into (select * from t where id <= 10) t
using (select 1 id from dual) d
ON (t.id = d.id)
when matched then update set c = 'iii';