0

I have below query which i am using oracle stored procedure. The query is running fine but i want to add condition in this query such that if the combination of row values with name,e_id,c_date,p_check already exist then do not insert this values.

INSERT INTO M_LOG(NAME, E_ID, C_DATE, STATUS, P_CHECK)
Select MAX(ML.NAME), ML.E_ID, C_DATE, 1, 'M Step_1' from F_LOG ML,DIR_LOG MD
WHERE ML.NAME != MD.NAME and ML.E_ID != MD.E_ID and MD.C_DATE = LAST_DAY(to_date(sysdate,'YYYYMMDD'))
GROUP BY ML.E_ID,C_DATE;
2
  • Use merge statement Commented Jan 17, 2018 at 15:19
  • Agree merge is more flexible, but you might also consider adding a not exists (select ...) to your existing insert. Commented Jan 17, 2018 at 15:56

2 Answers 2

1

You can use MERGE with a WHEN NOT MATCHED clause:

MERGE INTO M_LOG dst
USING (
  Select MAX(ML.NAME) AS name,
         ML.E_ID,
         C_DATE,
         1 AS status,
         'M Step_1 As p_check'
  from   F_LOG ML
         INNER JOIN DIR_LOG MD
         ON (   ML.NAME != MD.NAME
            AND ML.E_ID != MD.E_ID )
  WHERE  MD.C_DATE = LAST_DAY( TRUNC( sysdate ) )
  GROUP BY ML.E_ID,C_DATE
) src
ON (   src.name    = dst.name
   AND src.e_id    = dst.e_id
   AND src.c_date  = dst.c_date
   AND src.p_check = dst.p_check )
WHEN NOT MATCHED THEN
  INSERT (NAME, E_ID, C_DATE, STATUS, P_CHECK)
  VALUES ( src.name, src.e_id, src.c_date, src.status, src.p_check );
Sign up to request clarification or add additional context in comments.

1 Comment

sure i will try this
1

You could use NOT EXISTS.

 INSERT INTO m_log
            (
                name,
                e_id,
                c_date,
                status,
                p_check
            )
SELECT MAX(ml.name) name,
       ml.e_id,
       c_date,
       1          status,
       'M Step_1' p_check
FROM   f_log ml
WHERE  NOT EXISTS
       (
                SELECT   1
                FROM     dir_log md
                WHERE    ( ml.name = md.name
                               OR  ml.e_id = md.e_id )
                AND      md.c_date = LAST_DAY(TRUNC(SYSDATE)) )
                GROUP BY ml.e_id,
                         c_date; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.