oracle 如果表中存在相同的记录,如何防止插入

qacovj5a  于 2022-11-28  发布在  Oracle
关注(0)|答案(2)|浏览(212)

我有个疑问

INSERT INTO FCC_CS_WL_SOURCE_REQUEST_ID_MAP
(
"N_WL_SOURCE_REQUEST_ID",
"V_SOURCE_REQUEST_ID",
"V_TARGET_KEY",
"V_TARGET_INDEXNAME"
)
SELECT 
MAP_SEQ_TEST.nextval,
FCC_CUST_DIM.V_ALT_CUST_ID  AS "V_SOURCE_REQUEST_ID",
FCC_CS_MATCHED_RESULT_BULK.V_TARGET_KEY ,
FCC_CS_MATCHED_RESULT_BULK.V_TARGET_INDEXNAME 
FROM FCC_CS_MATCHED_RESULT_BULK INNER JOIN FCC_CUST_DIM 
ON FCC_CS_MATCHED_RESULT_BULK.V_SOURCE_KEY =FCC_CUST_DIM.V_CUST_INTRL_ID 
AND FCC_CUST_DIM.F_LRI_FL ='Y'
AND FCC_CUST_DIM.V_ALT_CUST_ID  IS NOT NULL 
AND FCC_CS_MATCHED_RESULT_BULK.N_RUN_SKEY =290

在这里,如果V_SOURCE_REQUEST_ID、V_TARGET_KEY、V_TARGET_INDEXNAME列值已经可用,并且与将要插入的值相同,我需要阻止向FCC_CS_WL_SOURCE_REQUEST_ID_MAP表中插入
如何修改此查询以实现此目的?

ve7v8dk2

ve7v8dk21#

使用MERGE陈述式:

MERGE INTO FCC_CS_WL_SOURCE_REQUEST_ID_MAP dst
USING (
  SELECT d.V_ALT_CUST_ID,
         b.V_TARGET_KEY ,
         b.V_TARGET_INDEXNAME 
  FROM   FCC_CS_MATCHED_RESULT_BULK b
         INNER JOIN FCC_CUST_DIM d
         ON b.V_SOURCE_KEY = d.V_CUST_INTRL_ID 
  AND    d.F_LRI_FL ='Y'
  AND    d.V_ALT_CUST_ID IS NOT NULL 
  AND    b.N_RUN_SKEY =290
) src
ON (
    src.V_ALT_CUST_ID      = dst.V_SOURCE_REQUEST_ID
AND src.V_TARGET_KEY       = dst.V_TARGET_KEY
AND src.V_TARGET_INDEXNAME = dst.V_TARGET_INDEXNAME
)
WHEN NOT MATCHED THEN
  INSERT (
    N_WL_SOURCE_REQUEST_ID,
    V_SOURCE_REQUEST_ID,
    V_TARGET_KEY,
    V_TARGET_INDEXNAME
  ) VALUES (
    MAP_SEQ_TEST.nextval,
    src.V_ALT_CUST_ID,
    src.V_TARGET_KEY,
    src.V_TARGET_INDEXNAME
  );
ego6inou

ego6inou2#

在SELECT中添加NOT EXISTS子句:

INSERT INTO FCC_CS_WL_SOURCE_REQUEST_ID_MAP
(
"N_WL_SOURCE_REQUEST_ID",
"V_SOURCE_REQUEST_ID",
"V_TARGET_KEY",
"V_TARGET_INDEXNAME"
)
SELECT 
MAP_SEQ_TEST.nextval,
FCC_CUST_DIM.V_ALT_CUST_ID  AS "V_SOURCE_REQUEST_ID",
FCC_CS_MATCHED_RESULT_BULK.V_TARGET_KEY ,
FCC_CS_MATCHED_RESULT_BULK.V_TARGET_INDEXNAME 
FROM FCC_CS_MATCHED_RESULT_BULK INNER JOIN FCC_CUST_DIM 
ON FCC_CS_MATCHED_RESULT_BULK.V_SOURCE_KEY =FCC_CUST_DIM.V_CUST_INTRL_ID 
AND FCC_CUST_DIM.F_LRI_FL ='Y'
AND FCC_CUST_DIM.V_ALT_CUST_ID  IS NOT NULL 
AND FCC_CS_MATCHED_RESULT_BULK.N_RUN_SKEY =290
AND NOT EXISTS (SELECT 1 FROM FCC_CS_WL_SOURCE_REQUEST_ID_MAP t1 WHERE V_SOURCE_REQUEST_ID = FCC_CUST_DIM.V_ALT_CUST_ID AND V_TARGET_KEY = FCC_CS_MATCHED_RESULT_BULK.V_TARGET_KEY AND V_TARGET_INDEXNAME = FCC_CS_MATCHED_RESULT_BULK.V_TARGET_INDEXNAME )

相关问题