views:

316

answers:

2

I want to have an 'updateinfo' table in order to record every update/insert/delete operations on another table.

In oracle I've written this:

CREATE TABLE updateinfo ( rnumber NUMBER(10), tablename VARCHAR2(100 BYTE), action VARCHAR2(100 BYTE), UPDATE_DATE date )

DROP TRIGGER TRI_TABLE;
CREATE OR REPLACE TRIGGER TRI_TABLE
AFTER DELETE OR INSERT OR UPDATE
ON demo
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN
if inserting then
insert into updateinfo(rnumber,tablename,action,update_date ) values(rownum,'demo', 'insert',sysdate);
elsif updating then
insert into updateinfo(rnumber,tablename,action,update_date ) values(rownum,'demo', 'update',sysdate);
elsif deleting then
insert into updateinfo(rnumber,tablename,action,update_date ) values(rownum,'demo', 'delete',sysdate);
end if;
-- EXCEPTION
-- WHEN OTHERS THEN
-- Consider logging the error and then re-raise
-- RAISE;
END TRI_TABLE;

but when checking updateinfo, all rnumber column is zero. is there anyway to retrieve the correct row number?

A: 

ROWNUM is not what you think it is. ROWNUM is a counter that has only a meaning within the context of one execution of a statement (i.e. the first resulting row always has rownum=1 etc.). I guess you are looking for ROWID, which identifies a row.

ammoQ
how can I use ROWID in the trigger then?
Freeman
ROWID does not identify a row. The unique identifier identifies a row. ROWID is a pointer to the physical location of a row a changes after and expdp impdp for instance.
Robert Merkwürdigeliebe
Robert: true, using the primary key of that table is prefereable to using ROWID
ammoQ
Freeman: As Robert said, it's best to use the primary key. To use rowid, you would have to change the data type of rnumber to varchar2 or rowid, then use "new.rowid" instead of rownum. But it's much better to use demo's primary key instead; if you use generated primary keys (usually an "id" column, populated from a sequence, or a "guid" column), use that datatype and put new.id resp. new.guid into rnumber. What you apparently plan to do is more complicated if you have concatenated primary keys for some tables.
ammoQ
+2  A: 

The only option is to use primary key column of your "demo" table.

ROWNUM is not what you are looking for, read the explanation.

ROWID looks like a solution, but in fact it isn't, because it shouldn't be stored for a later use.