-- MOPDB
DELETE FROM CT_MRDS.A_WORKFLOW_HISTORY t WHERE EXISTS (
  SELECT 1
  FROM
      CT_MOPDB.A_LOAD_HISTORY r
  WHERE
      r.WORKFLOW_NAME IN
        ('w_MOPDB_CSDB_REFERENCE_MONTHLY',
        'w_MOPDB_CSDB_REFERENCE_DAILY',
        'w_MOPDB_CSDB_RATINGS'
  )
  AND t.A_WORKFLOW_HISTORY_KEY = r.A_MOPDB_LOAD_SET_KEY
  AND NVL(t.ORCHESTRATION_RUN_ID,' ') = NVL(CAST(r.WLA_RUN_ID AS VARCHAR2(200)),' ')
  AND t.WORKFLOW_NAME = r.WORKFLOW_NAME
  AND NVL(t.WORKFLOW_START,SYSDATE) = NVL(r.LOAD_START,SYSDATE)
  AND NVL(t.WORKFLOW_END,SYSDATE) = NVL(r.LOAD_END,SYSDATE)
  AND NVL(t.WORKFLOW_SUCCESSFUL,' ') = NVL(CAST(NULL AS VARCHAR2(200)),' ')
  AND NVL(t.DBT_INVOCATION_ID,' ') = NVL(CAST(r.INFA_RUN_ID AS VARCHAR2(200)),' ')
  AND t.SERVICE_NAME = 'MOPDB'
);

-- ODS 
DELETE FROM CT_MRDS.A_WORKFLOW_HISTORY t WHERE EXISTS (
SELECT 1
FROM CT_ODS.A_LOAD_HISTORY r
WHERE WORKFLOW_NAME IN ('w_ODS_CSDB_DEBT', 'w_ODS_CSDB_DEBT_DAILY', 'w_ODS_CSDB_RATINGS_FULL')
  AND t.A_WORKFLOW_HISTORY_KEY = r.A_ETL_LOAD_SET_KEY
  AND NVL(t.ORCHESTRATION_RUN_ID,' ') = NVL( CASE WHEN r.WLA_RUN_ID is not null THEN CAST(r.WLA_RUN_ID AS VARCHAR2(200)) ELSE r.EXDI_CORRELATION_ID END,' ')
  AND t.WORKFLOW_NAME = r.WORKFLOW_NAME
  AND NVL(t.WORKFLOW_START,SYSDATE) = NVL(r.LOAD_START,SYSDATE)
  AND NVL(t.WORKFLOW_END,SYSDATE) = NVL(r.LOAD_END,SYSDATE)
  AND NVL(t.WORKFLOW_SUCCESSFUL,' ') = NVL(LOAD_SUCCESSFUL,' ')
  AND NVL(t.DBT_INVOCATION_ID,' ') = NVL(CAST(INFA_RUN_ID AS VARCHAR2(200)),' ')
  AND t.SERVICE_NAME = 'ODS'
);

COMMIT;