首页 > 解决方案 > 合并sql条件为空问题

问题描述

我有两个非常相似的 SQL 语句。其中一个工作,一个不工作。SQL 错误消息似乎具有误导性。你能弄清楚吗?

SQL 1 - 这工作得很好

    Merge into   t1 
    Using ( 
        Select art_ref_nr, channel, some_value From s1 ) t2
    On ( t1.art_ref_nr = t2.art_ref_nr and t1.channel = t2.channel
        and ( t1.datasource is null
            or (t1.datasource = 'no such value' ) -- only null values will be found
        ))
    WHEN MATCHED THEN UPDATE SET
        t1.some_value = t2.some_value
    ,   t1.datasource = 'value 1'
    ;

SQL 2——这失败了

    Merge into   t1 
    Using ( 
        Select art_ref_nr, channel, some_value From s1 ) t2
    On ( t1.art_ref_nr = t2.art_ref_nr and t1.channel = t2.channel
        and ( t1.datasource is null
       ))
    WHEN MATCHED THEN UPDATE SET
        t1.some_value = t2.some_value
    ,   t1.datasource = 'value 2'
    ;

SQL1 运行良好。SQL2 消息:

ON 子句中引用的列无法更新:字符串 原因:UPDATE SET 的 LHS 包含 ON 子句中引用的列

另一方面,我在两个 SQL 中都引用了子句“数据源”,因此错误消息不能完全正确。

问题似乎是有一次我只检查空值条目。但是为什么这会影响 SQL 逻辑呢?

许多问候,彼得

标签: sqloraclenullsql-merge

解决方案


我的猜测是您的第一个查询不会产生错误,因为永远找不到匹配的行。

对于第二个查询,它必须执行 UPDATE,但不能因为您将 UPDATE 列引用到 ON 子句中。

为了克服这个问题,尝试进入 WHERE 子句,ON 子句的部分引用您尝试更新的列:

Merge into   t1 
Using ( 
    Select art_ref_nr, channel, some_value From s1 ) t2
On (t1.art_ref_nr = t2.art_ref_nr and t1.channel = t2.channel)
WHEN MATCHED THEN UPDATE SET
    t1.some_value = t2.some_value
,   t1.datasource = 'value 2'
WHERE t1.datasource is null
;

推荐阅读