删除触发器未插入记录后的PL SQL

时间:2015-06-08 22:50:00

标签: sql plsql triggers

我有一个用PL / SQL编写的触发器,它应该将删除的记录插入另一个表中。

这是触发器:

CREATE OR REPLACE TRIGGER keepRemoved
AFTER DELETE
ON schema.table
FOR EACH ROW
DECLARE selection_id varchar2(10) := NULL;
BEGIN
    /* Check if deleted record already exists in destination table by populating variable with that value. */
     BEGIN
       SELECT a.primary_key
       INTO selection_id
       FROM [destinationTable] a
       WHERE a.primary_key = :old.removed_key
         AND a.condition_value = true
         AND a.condition_value2 = 42;
       EXCEPTION
         WHEN NO_DATA_FOUND THEN
           selection_id := NULL;
         WHEN OTHERS THEN
           selection_id := NULL;
      END;

    /* If selection_id is null, meaning that value doesn't exist in the destination table, insert deleted record in destination table */
      IF selection_id IS NULL THEN
        INSERT INTO [destinationTable] a
           (a.primary_key,
            a.user_id,
            a.column2,
            ...
            a.columnN)
        VALUES
            (:old.removed_key,
             SYS_CONTEXT('USERENV','AUTHENTICATED_IDENTITY'),
              123,
              ...
              'MoreText')
       END IF;
       EXCEPTION
         WHEN OTHERS THEN NULL;
 END;

问题在于删除记录时,destinationTable中没有填充任何内容。

对于上下文,我永远不会是用户删除记录。

2 个答案:

答案 0 :(得分:0)

你放在这里,就像Pseudocode不是真正的代码,所以我帮不了那么多,不过这是我的建议:

  1. 你有错误吗? 然后按照错误添加调试信息,在dbms_output.put_line的异常中编写一些代码进行检查。

  2. 确保您正在执行DML操作的同一个表上的触发器。

  3. 在删除"之前更改您的触发器以使用"

  4. 检查目标表中是否存在a.primary_key,否则将不执行插入。

答案 1 :(得分:0)

嗨请改变其他方式的逻辑,如波纹管使用计数而不是值和空匹配。你也不需要处理异常处理。

CREATE OR REPLACE TRIGGER keepRemoved
AFTER DELETE
ON schema.table
FOR EACH ROW
DECLARE 
selection_count pls_integer:=0
BEGIN
    /* Check if deleted record already exists in destination table by populating variable with that value. */
     BEGIN
       SELECT count(*)
       INTO selection_count
       FROM [destinationTable] a
       WHERE a.primary_key = :old.removed_key
         AND a.condition_value = true
         AND a.condition_value2 = 42;
       EXCEPTION     -- can remove this.
         WHEN NO_DATA_FOUND THEN
           selection_count := 0;
         WHEN OTHERS THEN
           selection_count := 1;  
      END;

    /* If selection_id is null, meaning that value doesn't exist in the destination table, insert deleted record in destination table */
      IF selection_count = 0 THEN
        INSERT INTO [destinationTable] a
           (a.primary_key,
            a.user_id,
            a.column2,
            ...
            a.columnN)
        VALUES
            (:old.removed_key,
             SYS_CONTEXT('USERENV','AUTHENTICATED_IDENTITY'),
              123,
              ...
              'MoreText')
       END IF;
       EXCEPTION
         WHEN OTHERS THEN NULL;
 END;