Oracle Merge delete子句,其中数据在目标中,但不在源中

时间:2019-02-12 19:23:38

标签: sql oracle plsql oracle12c

尝试从目标表中删除不在源表中的记录。

对象类型

CREATE OR REPLACE type dbo.P_REC AS OBJECT
(
    ATTR1    VARCHAR2(64 BYTE),
    ATTR2    VARCHAR2(128 BYTE),
    ATTR3    VARCHAR2(128 BYTE),
    ATTR4    VARCHAR2(128 BYTE)
);

集合类型

CREATE OR REPLACE type dbo.P_REC_LIST is table of P_REC;

存储过程

PROCEDURE testProc(tmpPList IN P_REC_LIST, resultCursor out sys_refcursor)

IF tmpPList.count > 0 THEN
MERGE INTO [targetTable] TT
        USING (SELECT abc.Attr1 abc.Attr2 FROM TABLE(tmpPList) abc) TMP
        ON (TT.Attr1 = TMP.Attr1)
      WHEN MATCHED THEN
        UPDATE SET TT.Attr2 = TMP.Attr2 
        DELETE WHERE TT.Attr1 NOT IN (SELECT Attr1 FROM TABLE(tmpPList))
      WHEN NOT MATCHED THEN
        INSERT (Attr1)
        VALUES (TMP.Attr1);
END IF;

目前,我可以从一个截断的表开始,然后插入部分开始工作。再次运行时,更新部分起作用。 但是,当从IE的tmpPList中删除一条记录时,该记录不再保留在源表中。

1 个答案:

答案 0 :(得分:0)

MERGE delete仅删除目标表中与ON子句和DELETE WHERE都匹配的行。

您可以在FULL JOIN查询中将TMPUSING一起使用,并使用标志来删除不匹配的行。

create or replace  PROCEDURE testProc(tmpPList IN P_REC_LIST)
AS
BEGIN
 IF tmpPList.count > 0 THEN
MERGE INTO targetTable tt
        USING ( with abc as
                 (
                  select * from TABLE(tmpPList)
                  )
                  select COALESCE(abc.attr1,t.attr1) as attr1,
                                     abc.attr2,CASE WHEN abc.attr1 IS NULL
                                           THEN 'Y' ELSE 'N' END 
                                          match_flag FROM abc
                          FULL JOIN targetTable t ON t.attr1 = abc.attr1
               ) tmp
        ON (tt.Attr1 = tmp.attr1)
      WHEN MATCHED THEN
         UPDATE SET tt.Attr2 = tmp.Attr2 
        DELETE WHERE match_flag = 'Y' --This flag to identify the unmatched row
      WHEN NOT MATCHED THEN
        INSERT (Attr1)
        VALUES (tmp.Attr1);
  END IF;
END testProc;
/

Demo