merge into中加入不等于条件判断

使用merge into,进行两张表的对比,如果条件符合则update,不符合可以insert。

这里的update和insert指的就是完整的update和insert的自语句。

所以可以做条件转移的。

如果想要将A表和B表中某个列是相同的,想要跟新某个不同,可以用语句。

我开始是这么想的:
报错:
无法更新 ON 子句中引用的列: “A”."SERVICE_VERSION"

merge into service_parameter a
using osb_service_info b on( a.service_code = b.osb_service_code and a.service_version != b.osb_service_version)
when matched then update set a.service_version=b.osb_service_version;

后面发现是不能用!=,on里面是不能用!=,on的作用是联表,这是个基础知识,对不起,我没想到,于是我上网搜发现有个老哥比我更骚,是这么想的:
把!=的条件假如到matched后面,我试了一下,语法还是报错,是不行的。

MERGE INTO Photo p
USING TmpPhoto tp
ON p.ProductNumberID = tp.ProductNumberID and p.SHA1 = tp.SHA1
WHEN MATCHED AND p.Rank = tp.Rank THEN
    UPDATE SET p.VerifiedDate = getDate()
WHEN MATCHED AND p.Rank != tp.Rank AND tp.Rank != 1 THEN
    UPDATE SET p.VerifiedDate = getDate(), p.Rank = tp.Rank, p.Active = 0
WHEN MATCHED AND p.Rank != tp.Rank AND tp.Rank = 1 THEN
    UPDATE SET p.VerifiedDate = getDate(), p.Rank = tp.Rank, p.Active = 1
WHEN NOT MATCHED THEN
    INSERT (ProductNumberID, Code, Extension, Rank, CreatedDate, VerifiedDate, FCTH, SHA1, Active)
    VALUES (tp.ProductNumberID, tp.Code, tp.Extension, tp.Rank, getdate(), getdate(), tp.FCTH, tp.SHA1, 0)
    OUTPUT inserted.NumberID as PhotoNumberID, inserted.ProductNumberID, inserted.SHA1, inserted.Rank INTO InsertedPhotos;

大佬出来指正,应该这样干:

MERGE INTO Photo p
USING TmpPhoto tp
    ON p.ProductNumberID = tp.ProductNumberID and p.SHA1 = tp.SHA1
    WHEN MATCHED 
     THEN
       UPDATE SET 
           p.VerifiedDate = getDate(),
           p.RANK = tp.RANK,
           p.Active = 
              (CASE
                WHEN p.Rank != tp.Rank AND tp.Rank != 1 THEN 0
                WHEN p.Rank != tp.Rank AND tp.Rank = 1 THEN 1
                ELSE p.Active END
             )
    WHEN NOT MATCHED THEN
        INSERT (ProductNumberID, Code, Extension, Rank, CreatedDate, VerifiedDate, FCTH, SHA1, Active)
        VALUES (tp.ProductNumberID, tp.Code, tp.Extension, tp.Rank, getdate(), getdate(), tp.FCTH, tp.SHA1, 0)
        OUTPUT inserted.NumberID as PhotoNumberID, inserted.ProductNumberID, inserted.SHA1, inserted.Rank INTO InsertedPhotos;

这样我就懂了,insert和update是完整的自语句,可以把联表后面的条件加到这里,那么我的sql就应该是:

merge into service_parameter a
using osb_service_info b on (a.service_code = b.osb_service_code  )
when matched then update set a.service_version=b.osb_service_version where a.service_version != b.osb_service_version

原问题路径
来自stackoverflow

你可能感兴趣的:(oracle,搞机)