我有两个非常相似的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中都引用了on-clause“datasource”,因此错误消息不能是完全正确的。
似乎问题是有一次我只检查空值条目。但是为什么这会影响SQL逻辑呢?
彼得,许多问候
我的猜测是你的第一个查询不会产生错误,因为永远找不到匹配的行。
对于第二个查询,它必须执行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
;