我有以下查询:
merge into A a
using (select :1 as x, :2 as y from sys.dual) tmp
on (a.x = tmp.x and
a.y = tmp.y)
when matched then
update set a.z = case when :3 = 1 then :4 else null end
when not matched then
insert
(
x,
y,
z
)
values
(
:1,
:2,
case when :3 = 1 then :4 else null end
)
有效,但是在以下情况下插入新记录:3为0.该记录的z值为null。我宁愿没有插入记录以防万一:3是0.
有没有办法做到这一点?
答案 0 :(得分:2)
来自11.1的文档(对于较新的版本也是如此):https://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9016.htm#SQLRF01606
如果希望Oracle数据库执行,请指定where_clause 仅当指定的条件为真时才插入操作。该 condition只能引用数据源表。 Oracle数据库 跳过条件不是的所有行的插入操作 真。
答案 1 :(得分:2)
根据[11.2文档],你可以在insert子句上有一个where子句,所以你的merge语句会变成这样:
merge into A a
using (select :1 as x, :2 as y from sys.dual) tmp
on (a.x = tmp.x and
a.y = tmp.y)
when matched then
update set a.z = case when :3 = 1 then :4 else null end
when not matched then
insert
(
x,
y,
z
)
values
(
:1,
:2,
case when :3 = 1 then :4 else null end
)
where :3 != 0 or :3 is null;
N.B。未测试