有的时候由于某种原因,我们需要监控对某个表的操作,例如:某个字段总是被莫名其妙的修改,此时就需要监控执行该操作的sql语句和操作人等信息,针对这种情况,9i和10g各有自己的监控方式。
1、oracle 9i
9i可以创建一个表,记录监控过程中感兴趣的东西
SQL> create table zk.monitor_sql(
2 username varchar2(30),
3 client_ip varchar2(100),
4 sql_text varchar2(4000),
5 table_name varchar2(30),
6 owner varchar2(30)
7 );
Table created
然后创建一个触发器,来监控对监控对象的操作:
SQL> CREATE OR REPLACE TRIGGER trigger_monitor_update_sql
2 BEFORE UPDATE ON zk.cm_busi_handle_200903
3 declare
4 n number;
5 stmt varchar2(4000);
6 sql_text ora_name_list_t;
7 begin
8 dbms_output.put_line(ora_sql_txt(sql_text));
9 n := ora_sql_txt(sql_text);
10 IF nvl(n,200)=200 THEN
11 raise_application_error(-20001,'ora_sql_txt未捕捉到任何语句.sql_txt未初始化');
12 ELSE FOR i IN 1..n LOOP
13 stmt := stmt || sql_text(i);
14 END LOOP;
15 dbms_output.put_line(stmt);
16 END IF;
17
18 insert into zk.monitor_sql(USERNAME, CLIENT_IP, SQL_TEXT, TABLE_NAME, OWNER)
19 values(user,sys_context('userenv','ip_address'),stmt,'T1','RAINY');
20 end;
21 /
Trigger created
这样,执行对表zk.cm_busi_handle_200903的update操作的用户名、ip地址、sql语句等信息就会保存在zk.monitor_sql表里了。其中关键的一步是:
ora_sql_txt(sql_text)
原型:ora_sql_txt(sql_text out ora_name_list_t)
官方解释:Returns the SQL text of the triggering statement in the OUT parameter. If the statement is long, it is broken into multiple PL/SQL table elements. The function return value shows the number of elements are in the PL/SQL table
但是ora_sql_txt(sql_text)只有在9i版本允许在dml触发器使用,在10g后该函数总是返回空,据说只能在ddl触发器使用。针对这一点的说法是:
On database versions 9.2.0.1 to 9.2.0.6 ora_sql_text works and returns the calling text for dml triggers, where as starting from 9.2.0.7 the behavior has changed and returns NULL.
2、oracle 10g
说是10g,9i应该也可以。其实我们可以结合v$session和v$sqltext来查看对某个表的操作,也可以采取如下的方式,创建一个策略:
SQL> begin
2 dbms_fga.add_policy(object_schema => 'zk', --schema名(默认当前操作用户)
3 object_name => 'cm_busi_handle_200903', --被操作object对象
4 policy_name => 'cm_busi_audit', --policy名(唯一)
5 audit_condition => 'process_id = 1', --条件
6 audit_column => 'oper_date', --列,如果有两个以上用“,”分隔
7 statement_types => 'update', --受影响的操作,如果有两个以上用“,”分隔
8 enable=>TRUE );
9 end;
10 /
查看捕获策略
select * from dba_audit_policies;
查看捕获信息
select timestamp,userhost,os_user,db_user,object_schema,object_name,statement_type,sql_text,policy_name from dba_fga_audit_trail order by timestamp;
策略的删除:
SQL> exec dbms_fga.drop_policy(object_schema=>'zk', object_name => 'cm_busi_handle_200903',policy_name => 'cm_busi_audit');
PL/SQL procedure successfully completed