在oracle中使用Merge语句触发

时间:2015-11-20 10:40:06

标签: oracle oracle10g

以下代码有什么问题,有些人可以帮我解决吗?

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;
/

错误: 错误(4,3):PL / SQL:忽略Sql stmt 错误(12,14):PL / SQL:ORA-00926:缺少关键字

感谢您提供的信息,我更改了以下代码并收到了新的错误。

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;
/

在test1表中插入记录时出现以下错误 ORA-30926:无法在源表中获得一组稳定的行

1 个答案:

答案 0 :(得分:1)

我怀疑你的合并声明中的所有源数据都已混淆了。你只想考虑插入的行,对吗?

我认为你的触发器应该是这样的:

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。如果:new.col5是日期列,则更改:

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

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

年有4位数(我猜你的意思是2016年,而不是1916年!)。