Tuesday, September 2, 2008

Using ORA_ROWSCN and SCN_TO_TIMESTAMP to find the last updated date or timestamp of a record.

Today, when I have gone through the Oracle Documentations, I came across two new things available in Oracle Database 10g – ORA_ROWSCN and SCN_TO_TIMESTAMP. Using this ORA_ROWSCN column and SCN_TO_TIMESTAMP function, the last date or timestamp can be found when a table or record updated.

ORA_ROWSCN

ORA_ROWSCN is a pseudocolumn of any table which has the most recent change information to a given row.

Here is an example to get the ora_rowscn value when a row updated.

SQL> connect scott/tiger@mydb
Connected.

SQL> SELECT ename FROM emp WHERE empno=7839;

ENAME
----------
KING

SQL> UPDATE emp SET ename='SABDAR' WHERE empno=7839;

1 row updated.

SQL> COMMIT;

Commit complete.

SQL> SELECT ora_rowscn,ename FROM emp WHERE empno=7839;

ORA_ROWSCN ENAME
---------- ----------
353845494 SABDAR

Here we got the scn value (353845494) of the empno record number 7839 when updated. Now we have to use the SCN_TO_TIMESTAMP function to convert an SCN, like ORA_ROWSCN 353845494 to the corresponding TIMESTAMP value.

SCN_TO_TIMESTAMP

SCN_TO_TIMESTAMP is a new function, in Oracle 10g, which is used to convert the SCN value generated, using ORA_ROWSCN coumn, into timestamp. SCN_TO_TIMESTAMP takes as an argument a number that evaluates to a system change number (SCN), and returns the approximate timestamp associated with that SCN. The returned value is of TIMESTAMP datatype. This function is useful any time you want to know the timestamp associated with an SCN.

Here we pass the scn value generated in the above query.

SQL> SELECT scn_to_timestamp(353845494) FROM emp WHERE empno=7839;

SCN_TO_TIMESTAMP(353845494)
-----------------------------------
02-SEP-08 03.20.20.000000000 PM

SCN_TO_TIMESTAMP function can also be used in conjunction with the ORA_ROWSCN pseudocolumn to associate a timestamp with the most recent change to a row.

SQL> SELECT scn_to_timestamp(ORA_ROWSCN) FROM emp WHERE empno=7839;

SCN_TO_TIMESTAMP(ORA_ROWSCN)
------------------------------------
02-SEP-08 03.20.20.000000000 PM

Regards,
Sabdar Syed,

http://sabdarsyed.blogspot.com/

No comments: