我有一个表table
,其中包含id, name, position, capture_date, modified_date, comments
列。
我正在尝试做一个让我疯狂的简单upsert
。
当表为空时,必须插入,但当它不为空时,它必须更新具有相同位置的注释列行,如果它不同,则必须插入新行而不是更新现有行。
当表为空时,我使用此merge语句来创建第一行。
这很好用。 但是,第二行必须是
1, john, 2, 01-JUL-15, 23-JUL-15, 'world'
在这种情况下,除了位置值为2之外,数据几乎相同,因此必须插入新行而不是将现有行的位置更新为2。 这就是我的合并声明正在做的事情。有任何想法可以解决这个问题。
merge into customers a
using(select 1 as customer_id, 'john' as customer_name, '1' as position, '01-JUL-15' as capture_date,
sysdate as modified_date, 'hello' as comments from dual) b
on(a.customer_id=b.customer_id)
when matched then
update set a.customer_id = b.customer_id, a.customer_name = b.customer_name,
a.position = b.position, a.capture_date= b.capture_date, a.modified_date = b.modified_date,
a.comments=b.comments
when not matched then
insert(a.customer_id, a.customer_name, a.position, a.capture_date, a.modified_date, a.comments)
values(b.customer_id, b.customer_name, b.position, b.capture_date, b.modified_date, b.comments)
我创建了sqlfiddle
答案 0 :(得分:1)
经验教训:
您收到的错误消息是:
ORA-38104: Columns referenced in the ON Clause cannot be updated: "A"."CUSTOMER_ID"
解决方案:从update子句中删除a.customer_id。
merge into customers a
using (select 1 as customer_id
,'john' as customer_name
,'1' as position
,'01-JUL-15' as capture_date
,sysdate as modified_date
,'hello' as comments
from dual) b
on (a.customer_id = b.customer_id)
when matched then
update
set a.customer_name = b.customer_name
,a.position = b.position
,a.capture_date = b.capture_date
,a.modified_date = b.modified_date
,a.comments = b.comments
when not matched then
insert
(a.customer_id
,a.customer_name
,a.position
,a.capture_date
,a.modified_date
,a.comments)
values
(b.customer_id
,b.customer_name
,b.position
,b.capture_date
,b.modified_date
,b.comments)