如何解决Oracle MERGE语句的局限性

问题描述

我想再更新两个变量,即“仅在更新earlyest_timestamp时最早的id”和“仅在latest_timestamp被更新时的latest_id”。有什么办法可以在下面的“合并”中执行此操作。否则,如果您在下面的“读取修改写入”问题上还有其他解决方案,请与我分享

BEGIN
MERGE INTO mytable
USING dual ON (id1 = ? AND ...)
WHEN NOT MATCHED THEN
INSERT (...) VALUES (...)
WHEN MATCHED THEN UPDATE 
SET earliest_timestamp = least(lEarliest,earliest_timestamp),latest_timestamp   = greatest(lLatest,latest_timestamp) 
    where earliest_timestamp > lEarliest or latest_timestamp < lLatest;
END;
/

解决方法

由于您正在更新,因此也无需使用dual表 一个表,则可以使用update语句而不是merge

update mytable
set earliest_timestamp = least(lEarliest,earliest_timestamp),latest_timestamp   = greatest(lLatest,latest_timestamp) 
    where earliest_timestamp > lEarliest or latest_timestamp < lLatest;