使用bar
类型的变量foo%ROWTYPE
,我可以在PL / SQL中同时执行INSERT
和UPDATE
:
INSERT INTO foo VALUES bar;
UPDATE foo SET ROW = bar WHERE id = bar.id;
但我如何做MERGE
?以下方法生成以下错误消息:
MERGE INTO foo USING bar ON foo.id = bar.id
WHEN MATCHED THEN UPDATE SET ROW = bar
WHEN NOT MATCHED THEN INSERT VALUES bar;
PL / SQL:ORA-00942:表或视图不存在
答案 0 :(得分:4)
MichaelS在上述线程中给出的答案应该可以正常工作。您收到的错误消息(ORA-38104:ON子句中引用的列无法更新:foo.id)表明您尝试执行类似以下操作:
merge into foo
using (select null from dual)
on (foo.id = bar.id)
when matched then update set foo.id = bar.id, foo.another_field = bar.another_field
when not matched then insert VALUES bar;
如错误所述,无法更新“ON”子句中引用的列。因此,以下工作正常:
merge into foo
using (select null from dual)
on (foo.id = bar.id)
when matched then update set foo.another_field = bar.another_field
when not matched then insert VALUES bar;
如果您确实需要更新foo.id,可以在此处找到解决方案:How to avoid ORA-3814 error on merge?
修改强>
可能的替代方法是执行以下操作:
update foo set row = bar where foo.id = bar.id;
if sql%rowcount = 0 then
insert into foo values bar;
end if;
这基本上等同于做与merge语句相同的事情。