-- 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_LM_ADHOC_ADJUSTMENT',
      'w_MOPDB_LM_BALANCESHEET',
      'w_MOPDB_LM_CSM_ADJUSTMENT',
      'w_MOPDB_LM_STANDING_FACILITY',
      'w_MOPDB_LM_CURRENT_ACCOUNTS',
      'w_MOPDB_LM_FORECAST',
      'w_MOPDB_LM_QRE_ADJUSTMENT',
      'w_MOPDB_LM_TTS'
  )
  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                 = CASE
                                          WHEN r.WORKFLOW_NAME = 'w_MOPDB_LM_STANDING_FACILITY' THEN 'w_MOPDB_LM_STANDING_FACILITIES'
                                          ELSE r.WORKFLOW_NAME
                                        END
  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_ADHOC_ADJUSTMENT_MSG',
      'w_ODS_LM_BALANCESHEET',
      'w_ODS_CSM_ADJUSTMENT_MSG',
      'w_ODS_LM_STANDING_FACILITY',
      'w_ODS_MRR_IND_CURRENT_ACCOUNT_ITEM',
      'w_ODS_QUARTERLY_ADJUSTMENT_MSG'
  )
  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                 = CASE 
                                          WHEN r.WORKFLOW_NAME = 'w_ODS_LM_STANDING_FACILITY'         THEN 'w_ODS_LM_STANDING_FACILITIES'
                                          WHEN r.WORKFLOW_NAME = 'w_ODS_MRR_IND_CURRENT_ACCOUNT_ITEM' THEN 'w_ODS_LM_CURRENT_ACCOUNT_ITEM'
                                          WHEN r.WORKFLOW_NAME = 'w_ODS_QUARTERLY_ADJUSTMENT_MSG'     THEN 'w_ODS_LM_QUARTERLY_ADJUSTMENT_MSG'
                                          ELSE r.WORKFLOW_NAME
                                        END
  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(r.LOAD_SUCCESSFUL,' ')
  AND NVL(t.DBT_INVOCATION_ID,' ')    = NVL(CAST(r.INFA_RUN_ID AS VARCHAR2(200)),' ')
  AND t.SERVICE_NAME                  = 'ODS'
);

COMMIT;