Autonomous Transaction in Oracle

An autonomous transaction is an independent transaction to the main or parent transaction. If an Autonomous transaction is started by another transaction it is not nested, but  independent of parent transaction.

Assume A is not completed because some unhandled exception occurred after B and B will be successful since it is an autonomous transaction.

Syntax

a) Autonomous transaction with package

create or replace package body pkg1
is
procedure add_log(error_text varchar2) is
PRAGMA autonomous_transaction;
begin
…………
…………
end add_log;
………….
…………..
end pkg1;

b) Autonomous transaction with standalone procedure/function

create or replace procedure add_log
is
PRAGMA autonomous_transaction;
begin
…………
…………
end add_log;

c) Autonomous transaction with triggers

create or replace trigger trg1
after insert on emp for each row
declare
PRAGMA autonomous_transaction;
……..
begin
………..
commit;
………..
end;

Usage

There are many situations you can use autonomous transactions but I would say error or event logging and auditing are the classic examples.

Below code is for basic error logging using autonomous transaction

SQL> desc log;
Name                                   Null?    Type
—————————————– ——– ————-
N                            NOT NULL NUMBER(38)
MYTEXT                                   VARCHAR2(100)
D                                              TIMESTAMP(6)

SQL> select * from log;

no rows selected

declare
v varchar2(1);
begin
add_log(‘before’);
v := ‘aa’;     — this will raise error
add_log(‘after’);
end;
/

declare
*
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character string buffer too small
ORA-06512: at line 5

SQL> select * from log;

N  MYTEXT  D
—————————————————————————
1   before      12-JUN-12 04.59.05.490000 PM

Even though pl/sql got error Autonomous Transaction procedure logged the error.

Word of caution :-

In-correct usage lead into more trouble,

Examples  :-

a) Autonomous Transaction with delete or update command.

b) Autonomous Transaction inside a trigger

They must be used very cautiously and use it only if you know exactly how transaction works in Oracle.

Advertisements

4 thoughts on “Autonomous Transaction in Oracle

  1. We can also call a different procedure for error logging which will have a commit. Why do we really need to use pragma autonomous transaction.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s