如何创建触发器以将在数据库上运行的所有查询存储到表中?

时间:2015-06-23 13:16:59

标签: sql oracle triggers cursor

我正在使用以下查询来实现此目的。在执行创建触发器的查询时,它正常工作,但是当我在创建触发器的表中插入一些东西时抛出错误。

create or replace trigger TESTTRIG
    after insert
        or update
        or delete
    on sourcetable
    declare
        v_text varchar2(1000);
        v_mask varchar2(100);
        cursor c1
          is
            select  sql_text
              from  v$open_cursor
              where sid = sys_context('USERENV','SID')
              order by last_sql_active_time desc;
    begin
        v_mask := case
                    when inserting then 'INSERT +INTO +<TABLE_NAME>( |\()'
                    when updating  then 'UPDATE +<TABLE_NAME> '
                    else 'DELETE( +FROM)? +<TABLE_NAME>( |$)'
                  end;
        open c1;
        loop
          fetch c1
            into v_text;
          exit when c1%notfound;
          if regexp_like(v_text,v_mask,'i')
            then
              insert into targettable('TIME_EXEC','SQL_TEXT') values (SYSDATE,v_text);
              exit;
          end if;
        end loop;
        close c1;
    end TESTTRIG;
/.

我在“sourcetable”表中插入任何内容时会得到一个ORA-04098。请帮忙。

1 个答案:

答案 0 :(得分:1)

为什么重新发明轮子? Oracle具有内置功能,可以完全满足您的需求:AUDIT。

  

使用AUDIT语句:

Track operations on a specific schema object. Auditing operations on schema objects apply to current sessions as well as to subsequent sessions.

请参阅页面底部的http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_4007.htm#SQLRF01107