Trigger with Merge statement in oracle

懵懂的女人 提交于 2020-01-17 06:33:00

问题


What is wrong with below code, can some help me to resolve it?

CREATE OR REPLACE TRIGGER TEST_TRI
   AFTER INSERT
   ON TEST1
   FOR EACH ROW WHEN (NEW.COL2 >= '01-MAY-16')
BEGIN
   IF INSERTING
   THEN
        MERGE INTO  TEST_HIST HIST
        USING  TEST1 T1
        ON (T1.NEW.COL1=HIST.COL2)
        WHEN MATCHED THEN
    UPDATE SET 
        HIST.COL5=NEW.COL5
        WHEN NOT MATCHED
        THEN
      INSERT INTO 
           VALUES (:NEW.COL1,:NEW.COL2,:NEW.COL3,:NEW.COL4,:NEW.COL5);                 
   END IF;    
END;
/

Error: Error(4,3):PL/SQL : Sql stmt ignored Error (12,14) : PL/SQL : ORA-00926: MISSING VALUES KEYWORD

Thanks for the info, i have changed code like below and getting new error.

CREATE OR REPLACE TRIGGER test_tri
   after INSERT
   ON test1
   FOR EACH ROW WHEN (NEW.col5 >= '01-MAY-16')
   DECLARE
   PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
   IF INSERTING
   THEN
        MERGE INTO  test_hist hist
        USING  test1 t1
        ON (t1.PACKAGE_ID=hist.PACKAGE_ID)
        WHEN MATCHED THEN
    UPDATE SET 
        hist.col5=t1.col5
        WHEN NOT MATCHED
        THEN
      INSERT (col1,col2, col3, col4, col5) 
           VALUES (:NEW.col1,:NEW.col2,:NEW.col3,:NEW.col4,:NEW.col5);                 
   END IF;  
   COMMIT;
END;
/

While inserting record in test1 table am getting below error ORA-30926: unable to get a stable set of rows in the source table


回答1:


You've got your source data all mixed up in your merge statement, I suspect. You only want to consider the rows being inserted, right?

I think your trigger should be something like:

CREATE OR REPLACE TRIGGER test_tri
   after INSERT
   ON test1
   FOR EACH ROW WHEN (NEW.col5 >= '01-MAY-16')
   DECLARE
   PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
   IF INSERTING
   THEN
        MERGE INTO test_hist hist
        USING (select :new.package_id, :new.col1, :new.col2, :new.col3, :new.col4, :new.col5
               from   dual) t1
          ON (t1.PACKAGE_ID=hist.PACKAGE_ID)
        WHEN MATCHED THEN
          UPDATE SET hist.col5=t1.col5
        WHEN NOT MATCHED THEN
          INSERT (col1, col2, col3, col4, col5)
          VALUES (t1.col1, t1.col2, t1.col3, t1.col4, t1.col5);
   END IF;  
   COMMIT;
END;
/

N.B. if :new.col5 is a date column, then change:

FOR EACH ROW WHEN (NEW.col5 >= '01-MAY-16')

to

FOR EACH ROW WHEN (NEW.col5 >= to_date('01/05/2016', 'dd/mm/yyyy'))

Years have 4 digits (I've guessed that you meant 2016, and not 1916!).



来源:https://stackoverflow.com/questions/33824580/trigger-with-merge-statement-in-oracle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!