-- MOPDB
DELETE FROM CT_MRDS.A_TASK_HISTORY_TARGET t WHERE EXISTS (
SELECT 
    A_LOAD_HISTORY_TARGET_KEY as A_TASK_HISTORY_TARGET_KEY,
    A_LOAD_SUBPROCESS_FK as A_TASK_HISTORY_KEY,
    TARGET_TABLE_NAME as TARGET_NAME,
    ROW_COUNT_APPLIED as ROW_COUNT_APPLIED,
    ROW_COUNT_REJECTED as ROW_COUNT_REJECTED,
    LOAD_SUCCESSFUL as LOAD_SUCCESSFUL,
    'MOPDB' AS SERVICE_NAME 
FROM
    CT_MOPDB.A_LOAD_HISTORY_TARGET r
WHERE
    TARGET_TABLE_NAME IN (
      'CSDB_DEBT',
      'CSDB_DEBT_DAILY',   
      'CSDB_INSTR_DESC_FULL',
      'CSDB_ISSUER_DESC_FULL'
)
AND t.A_TASK_HISTORY_TARGET_KEY      = r.A_LOAD_HISTORY_TARGET_KEY
AND t.A_TASK_HISTORY_KEY             = r.A_LOAD_SUBPROCESS_FK
AND NVL(t.TARGET_NAME,' ')                    = NVL(r.TARGET_TABLE_NAME,' ')
AND NVL(t.ROW_COUNT_APPLIED,0)                      = NVL(r.ROW_COUNT_APPLIED,0)
AND NVL(t.ROW_COUNT_REJECTED,0)                      = NVL(r.ROW_COUNT_REJECTED,0)
AND NVL(t.LOAD_SUCCESSFUL,' ')    = NVL(r.LOAD_SUCCESSFUL,' ')
AND t.SERVICE_NAME                   = 'MOPDB'
);

-- ODS
DELETE FROM CT_MRDS.A_TASK_HISTORY_TARGET t WHERE EXISTS (
SELECT 1
FROM
    CT_ODS.A_LOAD_HISTORY_TARGET r
WHERE
    TARGET_TABLE_NAME IN (
      'OU_CSDB_DEBT', 
      'OU_CSDB_DEBT_DAILY',
      'OU_CSDB_INSTR_DESC_FULL',
      'OU_CSDB_ISSUER_DESC_FULL'
)
AND t.A_TASK_HISTORY_TARGET_KEY      = r.A_LOAD_HISTORY_TARGET_KEY
AND t.A_TASK_HISTORY_KEY             = r.A_ETL_LOAD_SET_FK
AND NVL(t.TARGET_NAME,' ')                    = NVL(r.TARGET_TABLE_NAME,' ')
AND NVL(t.ROW_COUNT_APPLIED,0)                      = NVL(r.ROW_COUNT_APPLIED,0)
AND NVL(t.ROW_COUNT_REJECTED,0)                      = NVL(r.ROW_COUNT_REJECTED,0)
AND NVL(t.LOAD_SUCCESSFUL,' ')    = 'Y'
AND t.SERVICE_NAME                   = 'ODS'
);

COMMIT;