---
title: "Database Change Notification的一个例子"
author: "htallen"
date: "2010-04-30T10:12:37Z"
tags: []
categories: ["数据库"]
slug: "database-change-notification"
draft: false
lastmod: "2010-04-30T10:12:37Z"
id: 656762
url: "https://htallen.iteye.com/blog/656762"
---

转载自：http://blog.oracle.com.cn/html/86/t-126886.html

 

 

Change Notification

 

ORACLE提供的Databas Change Notification特性让我们可以通过Register的形式告诉数据库，  
用户对某些表的内容改变感兴趣。最常用的地方是，在数据发生变化后，刷新Mid-Tier的数据  
Cache.摘录一段文档内容  
\--------------------------------------------------------------------------------  
Database Change Notification is a feature that enables client applications to register  
queries with the database and receive notifications in response to DML or DDL  
changes on the objects associated with the queries. The notifications are published by  
the database when the DML or DDL transaction commits.  
During registration, the application specifies a notification handler and associates a set  
of interesting queries with the notification handler. A notification handler can be either  
a server side PL/SQL procedure or a client side C callback. Registrations are created  
on all objects referenced during the execution of the queries. The notification handler  
is invoked when a transaction subsequently changes any of the registered objects and  
commits.  
\--------------------------------------------------------------------------------

使用的对象以及关系  
        sys.chnf$\_desc &lt;-- sys.chnf$\_tdesc &lt;-- sys.chnf$\_rdesc

SQL&gt; desc sys.chnf$\_desc  
Element          Type                    
\---------------- ---------------------  
REGISTRATION\_ID  NUMBER                 
TRANSACTION\_ID   RAW(8)                 
DBNAME           VARCHAR2(30)           
EVENT\_TYPE       NUMBER                 
NUMTABLES        NUMBER                 
TABLE\_DESC\_ARRAY SYS.CHNF$\_TDESC\_ARRAY

SQL&gt; desc sys.chnf$\_tdesc  
Element        Type                    
\-------------- ---------------------  
OPFLAGS        NUMBER                 
TABLE\_NAME     VARCHAR2(64)           
NUMROWS        NUMBER                 
ROW\_DESC\_ARRAY SYS.CHNF$\_RDESC\_ARRAY

SQL&gt; desc sys.chnf$\_rdesc  
Element Type             
\------- --------------  
OPFLAGS NUMBER           
ROW\_ID  VARCHAR2(2000)

\--------------------------------------------------------------------------------  
下面提供一个简单的例子（首先满足系统权限要求）  
CONNECT / AS SYSDBA;  
GRANT CHANGE NOTIFICATION TO T2;  
GRANT EXECUTE ON DBMS\_CHANGE\_NOTIFICATION TO T2;  
\-- 如果有必要，设置参数job\_queue\_processes为非零（默认就是非零）  
ALTER SYSTEM SET job\_queue\_processes=4;

\------------------------------------------------------------------------------  
\-- create sample data  
\------------------------------------------------------------------------------  
create table ntfn\_batch as select rb.* from rps\_batch rb where rb.id = 2730006;

create table ntfn\_trans as  
select rt.*  
  from rps\_transaction rt  
where rt.original\_rps\_batch\_id = 2730006  
order by rt.id;

\------------------------------------------------------------------------------  
\-- create message table  
\------------------------------------------------------------------------------  
drop table ntfn\_msg;  
create table ntfn\_msg  
(  
  ora\_trans raw(8),  
  tab\_name  varchar2(30),  
  row\_id    varchar2(2000),  
  dt        date default sysdate  
);

\------------------------------------------------------------------------------  
\-- create procedure to process the callback when notification occurs  
\------------------------------------------------------------------------------  
/*  
You can create a PL/SQL stored procedure that the database server invokes in  
response to a change to a registered object. The procedure that receives the notification  
must have the following signature, where schema\_name is the name of the database  
schema and proc\_name is the name of the stored procedure:

PROCEDURE schema\_name.proc\_name( ntfnds IN SYS.CHNF$\_DESC )  
经过测试，这里的参数名称都必须一致 ntfnds  
\*/

create or replace procedure ntfs\_callback(ntfnds in sys.chnf$\_desc) is  
  l\_event\_type   number;  
  l\_ora\_trans\_id raw(8);  
  l\_numtables    number;  
  l\_op\_flag      number;  
  l\_tab\_name     varchar2(100);  
  l\_numrows      number;  
  l\_row\_id       varchar2(2000);  
begin  
  l\_event\_type   := ntfnds.event\_type;  
  l\_ora\_trans\_id := ntfnds.transaction\_id;  
  l\_numtables    := ntfnds.numtables;

  -- only concern table change  
  if l\_event\_type = dbms\_change\_notification.EVENT\_OBJCHANGE then  
    -- loop each table  
    for i in 1 .. l\_numtables loop  
      --------------------------------------------------  
      -- usually we call UTL\_HTTP to send a notification  
      -- to WEB Server, and here we only use some tables  
      --------------------------------------------------  
      l\_op\_flag  := ntfnds.table\_desc\_array(i).opflags;  
      l\_tab\_name := ntfnds.table\_desc\_array(i).table\_name;  
      -- get table name without schema name  
      l\_tab\_name := substr(l\_tab\_name, instr(l\_tab\_name, '.') + 1);  
     
      if bitand(l\_op\_flag, dbms\_change\_notification.ALL\_ROWS) = 1 then  
        -- no certain rowid  
        insert into ntfn\_msg  
          (ora\_trans, tab\_name)  
        values  
          (l\_ora\_trans\_id, l\_tab\_name);  
      else  
        -- loop each row in this table  
        l\_numrows := ntfnds.table\_desc\_array(i).numrows;  
        for j in 1 .. l\_numrows loop  
          l\_row\_id := ntfnds.table\_desc\_array(i).row\_desc\_array(j).row\_id;  
          insert into ntfn\_msg  
            (ora\_trans, tab\_name, row\_id)  
          values  
            (l\_ora\_trans\_id, l\_tab\_name, l\_row\_id);  
        end loop; -- end loop row  
      end if;  
    end loop; -- end loop table  
  end if;

  commit;  
end;  
/

\------------------------------------------------------------------------------  
\-- procession for registration and deregister  
\------------------------------------------------------------------------------  
\-- registration  
declare  
  l\_reg\_info sys.chnf$\_reg\_info;  
  l\_reg\_id number;  
  l\_qosflags number;  
  l\_temp number;  
begin  
  l\_qosflags := dbms\_change\_notification.QOS\_ROWIDS;  
  l\_reg\_info := sys.chnf$\_reg\_info('ntfs\_callback',l\_qosflags,0,0,0);  
  l\_reg\_id := dbms\_change\_notification.NEW\_REG\_START(l\_reg\_info);  
  -- register tables  
  select count(1) into l\_temp from ntfn\_batch b, ntfn\_trans t where b.id = t.original\_rps\_batch\_id;    
  dbms\_change\_notification.REG\_END;  
end;  
/

-- check register result  
select r.regid,r.table\_name from user\_change\_notification\_regs r;

-- deregister  
declare  
  l\_reg\_id number := 23;  
begin  
  dbms\_change\_notification.DEREGISTER(l\_reg\_id);  
end;  
/  

\------------------------------------------------------------------------------  
\-- do some change and check result after commit  
\------------------------------------------------------------------------------  
update ntfn\_batch b set b.rps\_application\_id=b.rps\_application\_id where rownum = 1;  
commit;  
update ntfn\_batch b set b.rps\_application\_id=b.rps\_application\_id;  
commit;  
update ntfn\_trans t set t.t2\_identifier = t.t2\_identifier;  
commit;

select to\_char(m.dt, 'yyyy-mm-dd hh24:mi:ss') dt,  
       m.ora\_trans,  
       m.tab\_name,  
       m.row\_id  
  from ntfn\_msg m  
order by 1, 3, 4;

SQL&gt;  
SQL&gt; select to\_char(m.dt, 'yyyy-mm-dd hh24:mi:ss') dt,  
  2         m.ora\_trans,  
  3         m.tab\_name,  
  4         m.row\_id  
  5    from ntfn\_msg m  
  6   order by 1, 3, 4;

DT                  ORA\_TRANS        TAB\_NAME                       ROW\_ID  
\------------------- ---------------- ------------------------------ --------------------------------------------------------------------------------  
2007-10-26 17:23:16 08004100D20D0100 NTFN\_BATCH                     AAFCIbAAHAAAM5AAAA  
2007-10-26 17:23:46 0A0061003ED50000 NTFN\_BATCH                     AAFCIbAAHAAAM5AAAA  
2007-10-26 17:24:26 0400200065D30000 NTFN\_TRANS                     AAFCIcAAHAAAM8IAAA  
2007-10-26 17:24:26 0400200065D30000 NTFN\_TRANS                     AAFCIcAAHAAAM8IAAB  
2007-10-26 17:24:26 0400200065D30000 NTFN\_TRANS                     AAFCIcAAHAAAM8IAAC  
2007-10-26 17:24:26 0400200065D30000 NTFN\_TRANS                     AAFCIcAAHAAAM8IAAD  
2007-10-26 17:24:26 0400200065D30000 NTFN\_TRANS                     AAFCIcAAHAAAM8IAAE  
2007-10-26 17:24:26 0400200065D30000 NTFN\_TRANS                     AAFCIcAAHAAAM8IAAF

8 rows selected

从这个结果可以分析出  
        执行了3个事务（简称1，2，3）  
        事务1，2更改了NTFN\_BATCH，事务3更改了NTFN\_TRANS