Is commit necessary to end autonomous transaction?

CREATE OR REPLACE TRIGGER TRIG_EMP
AFTER UPDATE
ON EMP
FOR EACH ROW
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
CNT NUMBER := 0 ;
BEGIN
--PROCE_TRIG_TEST_EMP;
SELECT COUNT(*)
INTO CNT
FROM EMP;
UPDATE EMP_bkp
SET COMM=999
WHERE ENAME ='SMITH';
-- COMMIT;
DBMS_OUTPUT.put_line('TRIG_EMP CALLED.. DONE: '||CNT);
END;
Error: "autonomous transaction detected "
if i open update n block commit code then error.
if i block both update n commit code then without commit code is running fine.
My Ques: If commit is necessary to end autonomous transaction then when i m blocking update n commit lines then too running without above error?
plz clear my concept..
pc

PC wrote:
thanks ..I will take care of it i.e. "IM".
In above code when I am blocking both "update & commit code lines" then there is no error raised by program.
I am using commit when I need that my "update transaction must be commit",if I am only taking "count of table emp" then no need of commit...
Like this I am not getting any exception..!Doing anything on the same table that caused the trigger to fire can lead to you getting a mutating table error, so care should be taken in that respect.
I got your point that I must commit and I will use it but here if I am using autonomous transaction without commit then I must get error but I am not facing ..plz guide me againThe point of an autonomous transaction is to effectively make Oracle spawn off a seperate transaction. Usually we consider that we have just a single transaction per session at any one time, but there are times, like when we need to log errors or audit something, that we want to ensure something get's written to a table, even if the transaction we are in needs to be rolled back or is about to raise an exception. In such cases we use an autonomous transaction to spawn the seperate transaction to perform that task. Good design would have that autonmous transaction as a seperate procedure to be called (rather than in the trigger itself) to keep it completely seperate from the current transaction, and thus when that seperate procedure finishes, any changes it has made must be committed or rolled back because the autonomous transaction that has been spawned is about to finish. Of course, if that procedure doesn't actually do any work on the database that requires committing or rolling back, then it's not necessary to issue one, but then there would be no need for an autonomous transaction in the first place.
So, with your trigger (let's ignore that fact that making the trigger autonomous is p!ss poor design), if you only do the count and don't do the update statement, then there is nothing to be committed, so there's no need for a commit statement, even if the trigger is defined as an autonomous transaction. But, if you include the update statement, then that spawned transaction must be committed before the trigger ends, so that the transaction is completed and control can return to the calling transaction. So, making your trigger autonomous doesn't mean that it must commit by itself... but making it autonomous and including something that needs committing, does mean it must commit.

Similar Messages

  • Autonomous Transactions and table locks

    Does a commit statement in an Autonomous Transaction block in PL/SQL release locks aquired in the master transaction block?
    e.g
    CREATE OR REPLACE PACKAGE test_auto_trans AS
    PROCEDURE mainproc;
    PROCEDURE testproc;
    END test_auto_trans;
    CREATE OR REPLACE PACKAGE BODY test_auto_trans AS
    /*****************Main Procedure*********************/
    PROCEDURE mainproc AS
    BEGIN
    LOCK TABLE a,b,c IN EXCLUSIVE MODE nowait;
    /*some processing involving tables a,b,c here. no commit done yet*/
    testproc();
    /* will the locks on a,b,c still be available here? */
    EXCEPTION
    WHEN others THEN
    dbms_output.put_line('Error');
    dbms_output.put_line(sqlcode);
    dbms_output.put_line(sqlerrm);
    RAISE;
    END mainproc;
    /*****************test Procedure*********************/
    PROCEDURE testproc AS
    PRAGMA AUTONOMOUS_TRANSACTION;
    BEGIN
    /*some processing using tables a,b,c here*/
    commit;
    EXCEPTION
    WHEN others THEN
    dbms_output.put_line('Error');
    dbms_output.put_line(sqlcode);
    dbms_output.put_line(sqlerrm);
    RAISE;
    END testproc;
    END test_auto_trans;
    /

    No transaction will release the locks held by another transaction. When you declare a stored proc to be PRAGMA AUTONOMOUS_TRANSACTION, it is essentially the same as if you logged in as the same user but in a different session.
    For example, if I have two sqlplus sessions running as user a, if I do an update in session1 and a delete and commit in session 2 I can still rollback in session 1.
    However, your psuedo code as posted will not work at all since the call to test_proc will block until you commit in the main proc, and since test_proc will never return, the main proc will never get to commit. It is exactly analogous to the following:
    session1> SELECT * FROM t;
            ID DESCR
             1 One
             2 Two
    session1> LOCK TABLE t IN EXCLUSIVE MODE nowait;
    Table(s) Locked.
    session1> UPDATE t SET descr = 'Un'
      2  WHERE id = 1;
    1 row updated.so far, this is your main proc. Now, in another session (which is equivalent to your autonomous transaction procedure), I do:
    session2> UPDATE t SET descr = 'Deux'
      2  WHERE id = 2;which as I type is still waiting on the commit from session 1. Therefore, I cannot get to commit the autonomous transaction which would return control to session1
    HTH
    John
    Message was edited by:
    John Spencer
    Sorry, I initially forgot to answer your actual question "what about DML statements like truncate". Since TRUNCATE is actually a DDL statement I will assume that is what you meant. My initial answer covers DML statements (except SELECT which will work).
    All DDL statements in Oracle go
    COMMIT
    DDL statement
    COMMIT
    since the initial commit requires a very brief exclusive lock, you will get an error like:
    ORA-00054: resource busy and acquire with NOWAIT specified
    Exactly as if you did:
    session1> LOCK TABLE t IN EXCLUSIVE MODE nowait;
    Table(s) Locked.then tried to do it again the another session
    session2> LOCK TABLE t IN EXCLUSIVE MODE nowait;
    LOCK TABLE t IN EXCLUSIVE MODE nowait
    ERROR at line 1:
    ORA-00054: resource busy and acquire with NOWAIT specified

  • Autonomous transactions not seeing posted data

    I want to add a button to a form to call a report. The users want to update data in the form, run the report then decide if the data is to be committed. I can post the changed data but the report doesn't see the posted data as Oracle starts a new session.
    The report performs various calculations and before it is run, the calculations are performed and data extracted to separate tables, the report then runs on the extracted data then the temporary table data is deleted.
    I thought autonomous transactions would be my solution. The data is posted within forms, the form then calls a database procedure which has the autonomous procedure declared, data extracted and committed to the temporary tables within the autonomous transaction (form data stays uncommitted), report runs using the extracted data. User could then decide if the amended data could then be committed to the database.
    The autonomous transaction does not seem to see the posted data. The procedure picks up the data 'pre post'. Any ideas on what I can do to get round this?
    Thanks in advance
    Karen Stalker

    Thanks for all the replies.
    My form that will call the report can call up to 12 other forms with data always posted and never committed until the user is prompted to on leaving the main form, or the user presses the commit key. I liked the idea of writing to a temporary table but the way this application is designed, this would mean a big rewrite of a lot of complicated forms. I would rather leave them alone as they work!!
    I could pass the record groups into the report - this would mean about 15 groups but that shouldn't be a problem except that there are a few child queries which I read can't be done that way. This may be a daft question but can I pass the record groups into the report and the record groups be then used in the after parameter trigger. There I could do all the necessary complications, write to my extract tables and then carry on as normal - i.e. the report gets the data from these extract tables.
    My best solution would be to get the reports and forms to run in the same session but how can I do this? As far as I'm aware, RUN_REPORT_OBJECT starts a new session. Hopefully someone knows how to get them in the same session.
    Thanks again
    Karen

  • AUTONOMOUS TRANSACTION(8I NEW FEATURE)에 대한 소개

    제품 : ORACLE SERVER
    작성날짜 : 2003-10-14
    AUTONOMOUS TRANSACTION(8I NEW FEATURE)에 대한 소개
    ==================================================
    autonomous transaction은 child transaction이라고도 불리우며 Oracle
    8i부터 제공되는 새로운 기능이며 현재까지는 pl/sql을 통해서만 구현이
    가능하지만 앞으로는 OCI까지 확장될 예정이다.
    pl/sql routine의 declare section 중 어떠한 곳에서라도 아래의 progma
    (compiler directive)를 지시함으로써 autonomous로 구분이 가능하다.
    pragma AUTONOMOUS_TRANSACTION;
    'pragma'는
    1) top-level anonymous blocks
    2) local, standalone or packaged functions and procedures
    3) methods of object types
    4) database triggers의 declare section 어디에서나 나타낼 수 있슴.
    아래의 경우에는 사용이 불가능.
    1) outside of a declase section
    2) nested block의 declare section
    3) package specification
    4) package body 중 procedure나 function definition 외부
    5) type body중 method definition의 외부
    autonomous transaction(tx) 내에서 명시적으로 rollback이나 commit을
    하여야 한다. 만일 이를 위반하였을 경우 main transcation 및 child
    transaction 모두 error 발생과 함께 rollback이 되게 된다.
    main transaction이 수행 중이고 child transaction이 아래의 상태의 경우 :
    1) autonomous transcation으로 선언된 code unit의 declare section에서
    기술된 statement가 수행 중인 동안 parent tx는 active로 남아있게 된다.
    2) "begin" 이후의 첫 executable step을 만나게 되면 parent transaction은
    유보되고 새로운 tx(child tx)가 시작된다.
    3) 이 code unit은 normal하게 수행이 되나 tx context는 새로운 transaction로
    설정된다.
    4) autonomous code unit에서 commit 이나 rollback 이 수행되면 이
    autonomous tx은 종료된다. 이 때까지 parent(main) tx는 계속 유보상태로
    남아 있으며 autonomous unit에서 계속되는 operation이 있다면 새로운 tx이
    시작된다.
    5) autonomous code unit에서 exit를 하게 되면 transaction context는
    parent로 전환이 된다.
    transaction context의 변경은 session parameter에 영향을 주지 않는다.
    따라서 parent transaction 에서 적용된 session parameter는 그대로 child
    tx에서도 영향을 미치게 된다.
    parent tx와 child tx는 서로 독립적이므로 lock 역시 공유하지 못한다.
    만일 parent tx에서 점유된 lock을 child에서 소유하고자 한다면 dead lock
    현상이 발생할 것이다. 이런 경우 ORA-60 이 발생되고 child tx는 자동적으로
    rollback 된다.
    <주의>
    ORACLE 8.1.6 README에서는 분산 transaction에서 autonomous tx 사용 시
    dead lock 발생 시 distributed lock timeout을 정상적으로 하지 못한다는
    주의사항이 소개되고 있슴.
    [예제]
    create table test_lobs (c1 number,c2 clob);
    create table msg (msg varchar2(120));
    create or replace function getlen (p1 in clob,
    p2 in number) return number as
    pragma AUTONOMOUS_TRANSACTION;
    len number;
    buf varchar2(120);
    tlen number;
    begin
    len := dbms_lob.getlength(p1);
    if len != 0 then
    dbms_lob.read(p1,len,1,buf);
    dbms_output.put_line('Value: '||buf);
    insert into msg values (buf);
    commit;
    end if;
    select dbms_lob.getlength(c2) into tlen
    from test_lobs where c1=p2;
    dbms_output.put_line('Length selected from table is '||tlen);
    return len;
    end;
    insert into test_lobs values (1,'Hello');
    insert into test_lobs values (2,'The quick brown fox');
    commit;
    declare
    cl1 clob;
    cl2 clob;
    ret number;
    begin
    select c2 into cl1 from test_lobs where c1 = 1 for update;
    select c2 into cl2 from test_lobs where c1 = 2;
    ret := getlen(cl1,1);
    dbms_output.put_line('Length of first row is '||ret);
    ret := getlen(cl2,2);
    dbms_output.put_line('Length of second row is '||ret);
    dbms_lob.writeappend(cl1,6,' there');
    ret := getlen(cl1,1);
    dbms_output.put_line('Length of first row is now '||ret);
    end;
    gives:
    Value: Hello
    Length selected from table is 5
    Length of first row is 5
    Value: The quick brown fox
    Length selected from table is 19
    Length of second row is 19
    Value: Hello there
    Length selected from table is 5
    Length of first row is now 11
    Selecting from the msg table gives 3 rows as follows:
    Hello
    The quick brown fox
    Hello there

  • Autonomous transaction in Tuxedo

    Our development team is using Bea Tuxedo as a middle tier in our transactions...we encountered a problem in using PRAGMA AUTONOMOUS_TRANSACTION in one of our services, 'ORA-00164: autonomous transaction disallowed within distributed transaction...'
    of course my question would be... what is the solution to this? or is there a solution to this?
    would really appreaciate if you could lend me a hand with this problem.

    CREATE TABLE GOKHAN_DENEME (EMPNO NUMBER(4) NOT NULL,
    ENAME VARCHAR2(10),
    EJOB VARCHAR2(9),
    DEPTNO NUMBER(2));
    INSERT INTO GOKHAN_DENEME VALUES (7369, 'SMITH', 'CLERK', 20);
    INSERT INTO GOKHAN_DENEME VALUES (7499, 'ALLEN', 'SALESMAN', 30);
    INSERT INTO GOKHAN_DENEME VALUES (7521, 'WARD', 'SALESMAN', 30);
    INSERT INTO GOKHAN_DENEME VALUES (7566, 'JONES', 'MANAGER', 20);
    CREATE TABLE GOKHAN_DENEME_2 (MGR NUMBER(4) NOT NULL,
    COMM NUMBER(7, 2));
    INSERT INTO GOKHAN_DENEME_2 VALUES (7369, 20);
    INSERT INTO GOKHAN_DENEME_2 VALUES (7499, 30);
    INSERT INTO GOKHAN_DENEME_2 VALUES (7521, 30);
    INSERT INTO GOKHAN_DENEME_2 VALUES (7566, 20);
    create or replace
    TRIGGER GOKHAN_DENEME_TRG1
    AFTER DELETE ON GOKHAN_DENEME FOR EACH ROW
    DECLARE
    PRAGMA AUTONOMOUS_TRANSACTION;
    BEGIN
    RAISE_APPLICATION_ERROR(-20000, 'ERRORRRRRR');
    END;
    create or replace
    TRIGGER GOKHAN_DENEME_2_TRG1
    AFTER DELETE ON GOKHAN_DENEME_2 FOR EACH ROW
    DECLARE
    PRAGMA AUTONOMOUS_TRANSACTION;
    BEGIN
    DELETE FROM GOKHAN_DENEME WHERE EMPNO = :OLD.MGR;
    COMMIT;
    END;
    the delete statement is:
    DELETE FROM GOKHAN_DENEME_2 WHERE MGR = 7566;
    the error mesage is:
    Error starting at line 74 in command:
    DELETE FROM GOKHAN_DENEME_2 WHERE MGR = 7566
    Error report:
    SQL Error: ORA-20000: ERRORRRRRR
    ORA-06512: at "DBO.GOKHAN_DENEME_TRG1", line 49
    ORA-04088: error during execution of trigger 'DBO.GOKHAN_DENEME_TRG1'
    ORA-06512: at "DBO.GOKHAN_DENEME_2_TRG1", line 10
    ORA-04088: error during execution of trigger 'DBO.GOKHAN_DENEME_2_TRG1'
    20000. 00000 - "%s"
    *Cause:    The stored procedure 'raise_application_error'
    was called which causes this error to be generated.
    *Action:   Correct the problem as described in the error message or contact
    the application administrator or DBA for more information.

  • Ora 02290 when using qms_transaction_mgt and autonomous transactions

    Hi all,
    I'm using the qms procedures:
    qms_transaction_mgt for openeing and closing transactions.
    Somewhere in my procedure when the transaction is opened i call another procedure which contains a autonomous transaction.
    The next time qms_transaction_mgt.close_transaction is called i get an ORA-02290: check constraint (HST65.QMS_NEED_TO_CLOSE_TRANSACTION) violated
    When i debug the qms_transaction_mgt.close transaction the g_current_trans_id variable is empty, which indicates the transaction is allready closed.
    When i remove the pragma autonomous_transaction statement and the commit statement from the procedure i call, the problem is resolved.
    Version information:
    Designer 9.0.2 with a with a Oracle 9i 9.2 database and Headstart 9i.
    Does anybody know how i can resolve this or if this is a bug and how to fix it?
    Thanks,
    Yvon

    Ian, Yvon,
    It is unfortunately a know restriction that the CDM RuleFrame component of both Headstart for Designer 6i and Headstart for Designer 9i doesn't work in combination with autonomous transactions.
    The reason is that the RuleFrame administration relies on information stored in 1. pl/sql package variables and 2. database tables. Using autonomous transactions (that involve CDM RuleFramed DML) causes this information to dissynchronize.
    A year ago I investigated the possibilities to make autonomous transactions possible with RuleFrame but unfortunately this is fundamental problem: RuleFrame wants to combine multiple DML-actions into one logical transaction (gards this with the "need_to_close_transaction" constraint), while autonomous transactions intend to to the opposite: commit a part of a transaction while the rest of the transaction still is posted/not committed.
    There is one exception: if you call an atonomous procedure that does DML on a non-ruleframe-enabled table (no TAPI triggers that intend to open/close the transaction, no CAPI etc), everything functions.
    Problem explanation:
    ====================
    1. Outer transaction is opened (by front end or TAPI triggers of first DML)
    2. DML takes place
    3. Autonomous transaction-procedure is called
    4. Auto-transaction again tries (and succeeds!) to open the transaction, it doesn't see that the transaction is opened (db table qms_transactions is empty for the autonomous transaction on query)
    5. DML within auto-transaction is posted
    6. Auto-transaction closes transaction
    7. Auto-transaction is committed
    8. Outer transaction thinks the transaction is already closed, because the auto-transaction cleaned out the package variables when it closed the transaction.
    9. Commit of the outer transaction fails as the deferred check constraint need_to_close_transaction avoids this to happen (rollback takes place because of this violation).
    Hope this helps
    Kind Regards
    Marc Vahsen
    Headstart Team Oracle NL

  • Autonomous Transactions usage in PL/SQL anonymous block coding

    Hi,
    I am trying to incorporate Autonomous Transaction for our work. I am using the tables provided below,
    CREATE TABLE T1
    F1 INTEGER,
    F2 INTEGER
    CREATE TABLE T2
    F1 INTEGER,
    F2 INTEGER
    insert into t1(f1, f2)
    values(20, 0)
    insert into t2(f1, f2)
    values(10, 0)
    Now, when I use the code snippet given below, it is working as expected.
    create or replace procedure p1 as
    PRAGMA AUTONOMOUS_TRANSACTION;
    begin
         update t2
         set f2 = 25
         where f1 = 10;
         commit;
    end;
    declare
    PRAGMA AUTONOMOUS_TRANSACTION;
    a integer;
    begin
         update t1
         set f2 = 15
         where f1 = 20;
         p1();
         rollback;
    end;
    Here, updation in t2 table is commited and t1 is rolled back, it is working as
    expected. I would like to achieve the same functionality through PL/SQL
    anonymous block coding, to do this, I use the following code snippet,
    declare
    PRAGMA AUTONOMOUS_TRANSACTION;
    a integer;
    begin
         update t1
         set f2 = 15
         where f1 = 20;
         begin
              update t2
              set f2 = 35
              where f1 = 10;
              commit;
         end;
         rollback;
    end;
    Here, data in both the tables are commited, how do I change it to work as I
    mentioned above like committing t2 alone, please help, thank you.
    Regards,
    Deva

    Can you explain what you're trying to accomplish from a business perspective? This doesn't look like a particularly appropriate way to use autonomous transactions, so you may be causing yourself problems down the line.
    That said, padders's solution does appear to work for me
    SCOTT @ nx102 Local> CREATE TABLE T1
      2  (
      3  F1 INTEGER,
      4  F2 INTEGER
      5  )
      6  /
    Table created.
    Elapsed: 00:00:01.03
    SCOTT @ nx102 Local>
    SCOTT @ nx102 Local>
    SCOTT @ nx102 Local> CREATE TABLE T2
      2  (
      3  F1 INTEGER,
      4  F2 INTEGER
      5  )
      6  /
    Table created.
    Elapsed: 00:00:00.00
    SCOTT @ nx102 Local>
    SCOTT @ nx102 Local> insert into t1(f1, f2)
      2  values(20, 0)
      3  /
    1 row created.
    Elapsed: 00:00:00.01
    SCOTT @ nx102 Local>
    SCOTT @ nx102 Local> insert into t2(f1, f2)
      2  values(10, 0)
      3  /
    1 row created.
    Elapsed: 00:00:00.01
    SCOTT @ nx102 Local> commit;
    Commit complete.
    Elapsed: 00:00:00.01
    SCOTT @ nx102 Local> DECLARE
      2     a INTEGER;
      3 
      4     PROCEDURE update_t2
      5     IS
      6        PRAGMA AUTONOMOUS_TRANSACTION;
      7     BEGIN
      8        UPDATE t2
      9           SET f2 = 35
    10         WHERE f1 = 10;
    11 
    12        COMMIT;
    13     END update_t2;
    14  BEGIN
    15     UPDATE t1
    16        SET f2 = 15
    17      WHERE f1 = 20;
    18    
    19     update_t2;
    20 
    21     ROLLBACK;
    22  END;
    23  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.04Have you done something else that would cause a deadlock?
    Justin

  • Set up autonomous transaction with error

    Hi, Guys:
    I try to set up autonomous transaction as a process after button pressed, I have this error:
    1 error has occurred•ORA-06550: line 4, column 8: PLS-00710: Pragma AUTONOMOUS_TRANSACTION cannot be specified here
    Could anyone give me a hint?
    declare
    PRAGMA AUTONOMOUS_TRANSACTION;
    begin
      if :P2200_CURRENT_SETTING='Y' then
        update SOR_APEX_CONFIG
        set CURRENT_SETTING='N';
      end if;
      update SOR_APEX_CONFIG
      set APEX_SERVER=:P2200_APEX_SERVER,
      PORT=:P2200_PORT,
      APEX_STRING=:P2200_APEX_STRING,
      CURRENT_SETTING=:P2200_CURRENT_SETTING,
      APP_ID=:P2200_APP_ID,
      CONFIG_DATE=sysdate
      where ROWID=:P2200_ROWID;
       commit;
    end;I am using Oracle 11g, APEX 4.1
    Edited by: lxiscas on Aug 23, 2012 1:56 PM

    Hi Ixiscas,
    I am able to reproduce this issue on my APEX Installation (4.1, 11g).
    The reason maybe that the code is not executed directly but via dbms_sys_sq.parse_as_user().
    My suggestion would be to move the functionality to a pl/sql procedure in the parsing schema and call this procedure in the page process.
    Regards
    Marc
    Edited by: telemat on Aug 23, 2012 11:46 PM

  • Pipeline function raised ORA-06519: active autonomous transaction detected

    Hi All,
    My name is John and I've got a problem which I need to share with all of you guru and experts. I've created the following pipeline function under the Oracle user ABC:
    CREATE OR replace FUNCTION SomeFunction(p_from_date DATE, p_to_date DATE) RETURN T_TAB_A pipelined
    IS
    PRAGMA autonomous_transaction;
    BEGIN
    DELETE FROM temp_rcm;
    INSERT INTO temp_rcm
    SELECT * FROM int.facility fd,
    int.capacity co
    WHERE co.resource_name = fd.resource_name
    AND co.trade_date = fd.trade_date
    AND co.trade_date BETWEEN p_from_date AND p_to_date;
    COMMIT;
    FOR rec IN (SELECT co.*
    FROM temp_rcm co
    left join int.outage o
    ON ( o.flag = 'Y'
    AND o.reason_flag = 'F'
    AND o.INTERVAL = co.INTERVAL
    AND co.resource_name = o.resource_name )
    ORDER BY co.INTERVAL,
    co.name) LOOP
    pipe ROW (T_A( rec.INTERVAL, rec.trade_date,
    rec.resource_name,rec.day_of_week_long, rec.working_day, rec.peak));
    END LOOP;
    RETURN;
    END SomeFunction;
    I was able to compile and create the SomeFunction function successfully but when I executed it using the following command:
    select * from table(SomeFunction(to_date('01/01/2010',to_date('01/01/2010')));
    I was returned with the Oracle error - ORA-06519: active autonomous transaction detected and rolled back
    I have searched through the web, such Oracle error occurs whenever the function has a missing 'COMMIT' or 'ROLLBACK' command inside an autonomous_transaction. But the fact is I have already included the 'COMMIT;' in the function. I suspected that the error was caused by the tables which I queried against (like int.facility and int.capacity) were all views that belonged to another schema called int. Or is that something that I miss in the function? Thank you for your time and assistance.
    Regards,
    John

    johnwanng wrote:
    Hi Guys,
    Thank you for all your feedback. In addition to your reply, Bill, can you spare some time and provide us a simple example of the steps involved to implement the 'correct' implementation based on the queries that I've used. As I do not understand your vanilla approach. Much appreciated and thank you for the time again.
    Regards,
    JohnIf I had to guess, Billy may have meant something like this (untested):
    CREATE OR REPLACE FUNCTION SomeFunction
    ( p_from_date IN int.facility.trade_date%TYPE
    , p_to_date   IN int.facility.trade_date%TYPE
    RETURN SYS_REFCURSOR
    AS
         rcur     SYS_REFCURSOR;
    BEGIN
         OPEN rcur FOR
              SELECT co.interval
                   , co.trade_date
                   , co.resource_name
                   , co.day_of_week_long
                   , co.working_day
                   , co.peak
              FROM   int.capacity co
              JOIN   int.facility fd        ON fd.resource_name = co.resource_name
                                           AND fd.trade_date    = co.trade_date
              LEFT OUTER JOIN int.outage o  ON o.interval       = co.interval
                                           AND o.resource_name  = co.resource_name
              WHERE  co.trade_date BETWEEN p_from_date AND p_to_date
              AND    o.reason_flag = 'F'
              AND    o.flag        = 'Y'
              ORDER BY co.interval
                     , co.name
         RETURN rcur;
    END;
    /I made the following modifications:
    1. I set the input parameter data types to match that of the table column you are checking against. A good practice to get into.
    2. Removed the autonomous transaction and inserting into a temp table. In Oracle it's a good practice to perform everything in a single SQL statement if possible.
    3. Changed the return data type to a SYS_REFCURSOR
    Hope this helps and provides a good example.

  • Help on autonomous transaction

    Hi All.
    I've been testing the use of AT and have come to the following doubt:
    The example below is based on the Summit Schema:
    1) Log table to insert audit info:
    create table traza_error
    (co_error integer not null
    ,tx_error varchar2(4000) not null
    ,fe_error date not null
    ,usuario_error varchar2(30)
    ,equipo_error varchar2(200))
    2) Procedure to insert info on log table:
    create or replace procedure registra_log_error is
    pragma autonomous_transaction;
    r_traza traza_error % rowtype;
    begin
    r_traza.co_error := sqlcode;
    r_traza.tx_error := substr(sqlerrm,1,4000);
    r_traza.fe_error := sysdate;
    r_traza.usuario_error := user;
    r_traza.equipo_error := sys_context('userenv','terminal');
    insert
    into traza_error
    values r_traza;
    commit;
    end;
    3) Procedure to insert rows on S_EMP table:
    create or replace procedure registra_empleado (r_emp in s_emp % rowtype) is
    begin
    insert
    into s_emp
    values r_emp;
    end registra_empleado;
    4) Anonymous block to insert rows on S_EMP table and raise error:
    declare
    r_emp s_emp % rowtype;
    begin
    r_emp.id := 98;
    r_emp.last_name := 'Perez';
    r_emp.first_name := 'Pedro';
    r_emp.dept_id := 34;
    registra_empleado (r_emp);
    r_emp.id := 99;
    r_emp.last_name := 'Perez';
    r_emp.first_name := 'Pablo';
    r_emp.dept_id := 111;
    registra_empleado (r_emp);
    commit;
    dbms_output.put_line('Registrado el empleado: '||r_emp.first_name||','||r_emp.last_name);
    exception
    when others then
    dbms_output.put_line('Ocurrió el error '||sqlcode||' se registrará en la auditoria de Log');
    registra_log_error;
    end;
    5) Comments:
    Anonymous block must inserts two records, the first one succeeds, second must fail as dept_id 111 is not a valid id (fk with s_dept).
    My point is that, as i understand, the main block (anonymous) must fail an insert no records. However when autonomous transaction is called(registra_log_error) the commit in it , commit boths, the log error record and also the first insert on the S_EMP table.
    From my understanding of AT, the pragma starts a new transaction. For me, that implies another logical unit of work, and as though it should only commit the log record, not boths.
    The whole idea of the log error routine is to be independent of the main transaction, as would happen on a real world situation.
    Please, anyone, clarify on this one ....
    Help will be greatly appreciated ....!

    Your understanding of how autonomous transactions should work is correct - the work of the autonomous transaction is committed independently of the main transaction.
    From a quick look at your example, this has nothing to do with the autonomous transaction nor its commit boundaries but everything to do with having an exception handler that does not raise or rollback and the difference in this regard between handled and unhandled exceptions.
    See the difference between this:
    SQL> create table t1
      2  (col1 number primary key);
    Table created.
    SQL> begin
      2   insert into t1 values (1);
      3   insert into t1 values (1);
      4  exception when dup_val_on_index then null;
      5  end;
      6  /
    PL/SQL procedure successfully completed.
    SQL> select * from t1;
          COL1
             1
    SQL> rollback;
    Rollback complete.
    SQL> select * from t1;
    no rows selectedand this:
    SQL>  begin
      2    insert into t1 values (1);
      3    insert into t1 values (1);
      4   end;
      5  /
    begin
    ERROR at line 1:
    ORA-00001: unique constraint (RIMS.SYS_C00167927) violated
    ORA-06512: at line 3
    SQL> select * from t1;
    no rows selected
    SQL> or this:
    SQL> begin
      2   insert into t1 values (1);
      3   insert into t1 values (1);
      4  exception when dup_val_on_index then
      5   -- do some stuff then
      6   raise;
      7  end;
      8  /
    begin
    ERROR at line 1:
    ORA-00001: unique constraint (RIMS.SYS_C00167927) violated
    ORA-06512: at line 6
    SQL>  select * from t1;
    no rows selected
    SQL>

  • Whats the use of having pragma autonomous transaction

    Hii All,
    The below is the procedure developed by our predecessors.We are making use of this for writing our debug messages.
    I'm aware of pragma autonomous transaction ,this allows my code to run independently of the calling program.
    But here we are just using utl_File and we are neither using any DML(Inserting error messages into a table) or DDL statements in the below code.
    What is real use of having pragma autonomous transaction.???This code is working in the same way even without the pragma...I dont' find any difference .
    Please let me know the use of having pragma autonomous transaction in the below procedure and where it actually comes into usage.
    Create or replace Procedure logmesg
    p_file_name          in          varchar2,
    p_mesg_text          in          varchar2,
    p_dir_path          in          varchar2 default fn_get_debug_path,
    p_file_ext          in          varchar2 default 'log',
    p_append_flag     in          varchar2 default 'Y'
    ) Is
              pragma autonomous_transaction;
              l_utl_file                    utl_file.file_type;
              l_append_flag               varchar2(1);
              l_mesg_text                    varchar2(32000);
              l_file_name                    varchar2(3000);
              l_dir_path                    varchar2(32000);
              l_delimeter_occurance     number;
              l_buffer_str               varchar2(32000);
    Begin
              if trim(p_dir_path) is null then
                   l_dir_path     := fn_get_debug_path ;
              else
                   l_dir_path := p_dir_path;
              end if;
              l_mesg_text := p_mesg_text;
              l_append_flag := nvl(p_append_flag,'Y');
              l_file_name     := p_file_name||'_'||to_char(sysdate,'ddmmyyyyhh')||'.'||p_file_ext;
              l_append_flag := Case     l_append_flag
                                       When 'Y' then 'a'
                                       When 'N' then 'w'
                                   End;--l_append_flag
              Begin
                   l_utl_file := utl_file.fopen(l_dir_path,l_file_name,l_append_flag);
              Exception
                   When Others Then
                        l_utl_file := utl_file.fopen(l_dir_path,l_file_name,'w');
              End;
              if dbms_lob.getlength(l_mesg_text) > 32000 then
                   loop
                        exit when dbms_lob.getlength(l_mesg_text) < 32000;
                        l_delimeter_occurance := dbms_lob.instr(l_mesg_text,chr(32),1,1);
                        l_buffer_str := dbms_lob.substr(l_mesg_text,l_delimeter_occurance-1);
                        utl_file.put_line(l_utl_file,l_buffer_str);
                        l_mesg_text := dbms_lob.substr(l_mesg_text,l_delimeter_occurance+1);
                        utl_file.fflush(l_utl_file);
                   end loop;
              end if;
              utl_file.put_line(l_utl_file,l_mesg_text);
              utl_file.fflush(l_utl_file);
              utl_file.fclose(l_utl_file);
    End logmesg;
    /Here

    Please let me know the use of having pragma autonomous transaction in the below procedure and where it actually comes into usage.Seems it is redundant in that procedure, and doesn't add any value, since the procedure isn't doing anything 'transactional'.
    I would remove it.

  • Autonomous transaction in trigger

    Hi,
    Can we use commit within a database trigger? I think yes if we use autonomous transaction in that trigger.
    Please confirm and if it is correct please provide an example of this.
    Thanks,
    Mrinmoy

    user3001930 wrote:
    Can we use commit within a database trigger? I think yes if we use autonomous transaction in that trigger.
    Please confirm and if it is correct please provide an example of this.Yes, you can commit in an autonomous transaction within a trigger, but bear in mind that that is only committing the transcation that is autonomous, not the original sessions changes. So if you're expecting to be able to commit the data in your present transaction that has caused the trigger you are mistaken.
    Perhaps the simplest way to look at an autonomous transaction is as though the database has started up a seperate session to execute some transactions, and before execution can return to the original session it must commit or rollback what it's done in that second session, however that second session cannot influence the transactions taking place in the first session.

  • Using Autonomous Transaction in dbms_job on Oracle 8.1.6

    I am submitting a package.procedure job to run using dbms_job.run procedure on Oracle 8.1.6 database.
    The package.procedure calls another autonomous transaction procedure to handle the exceptions.
    The dbms_job.run works fine if no exception is encountered, however if
    there were to be an exception, resulting in a call to auto. trans.,
    I encounter -
    SQL> exec dbms_job.run(152404);
    ERROR:
    ORA-01041: internal error. hostdef extension doesn't exist
    begin dbms_job.run(152404); end;
    ERROR at line 1:
    ORA-03113: end-of-file on communication channel
    If I submit this thru an Oracle Form, the form also throws me out for this unhandled exception.
    When I comment out the auto. trans. procedure in exception handling section, dbms_job.run works fine.
    Also when I directly execute the package.procedure without submitting thru dbms_job, the auto. trans. is able to handle the exception.
    Does it mean auto. trans. is not compatible with dbms_job in Oracle 816 or there is any patch out there ?
    Any clues will be highly appreciated.
    thanx

    There is a rollback before the auto. trans. guy gets called.
    The auto. pragma itself gets committed too and is also rollbacked in event of a failure.
    The transaction works fine in all situations when not submittted thru dbms_job.run
    null

  • Defer persistence in create to the end of transaction..

    How I defer the persistence "insert in the database" to the end of transaction instead of the EJBCreate Method ?
    In the EJB Spec ...
    "The container may create the representation of the entity in the database immediately, or it can
    defer it to a later time (for example to the time after the matching ejbPostCreate<
    METHOD>(...) has been called, or to the end of the transaction), depending on the
    caching strategy that it uses."
    Thanks

    Hi Pablo -
    In the 903 release, there is an attribute you can set for CMP entity beans that defines when the updates to the database occur.
    The attribute is:
    delay-updates-until-commit (true | false) "true"
    This is defined in the orion-ejb-jar.xml file for your deployed application.
    http://xmlns.oracle.com/ias/dtds/orion-ejb-jar.dtd
    This should be covered in the 903 EJB Developer's Guide, see,
    http://otn.oracle.com/docs/products/ias/doc_library/903doc_otn/generic.903/a97677/dtdxml.htm#634210
    Hope that helps.
    -steve-

  • Exam 1z0-147 - Autonomous transactions in triggers

    hi all,
    I am taking my 1z0-147 exam soon and I would like to know if anyone can help me out with this dilema.
    all the practice material I have used states that transactional statements such as COMMIT cannot be performed inside a trigger. However this is not completely true as you can perform commits and other ddl etc inside a trigger if you declare it as an autonomous transaction...
    I would like to know if anyone can reccommend which approach I should take for answering the real exam questions. which answer is right? Can I perform a commit inside a trigger or not?
    Thanks in advance!
    Steve

    user11694872 wrote:
    hi all,
    I am taking my 1z0-147 exam soon and I would like to know if anyone can help me out with this dilema.
    all the practice material I have used states XXXXXXXXXXXXXXXX. However this is not completely true as YYYYYYYYYYYYYYYY..
    I would like to know if anyone can reccommend which approach I should take for answering the real exam questions. which answer is right? Can ZZZZZZZZZZZZZZZZZZZ or not?
    Thanks in advance!
    SteveIts probably bad practice to ask questions on certification related questions here, and your question might fail a strict interpretation of the Non-disclosure agreement.
    You should probably try to get a response from the source of your legitimately obtained authorized practice questions:
    [http://blogs.oracle.com/certification/2009/05/the_route_you_choose.html]
    [www.certguard.com]
    This also means I best not comment directly on this, especially as I have taken 1z0-147
    And Its why I've censored my quoting of your response
    The key thing is to remember that the answer required is best answer from information gained in the question (and an excepton not on syllabus in unlikely to contribute to best answer ... but thats a judgement call).
    If you really feel an ambiguity during the exam I think a comment button is present and you may care to use it ... but of course this loses time ... and probably will you you more than you gain. You could then possilby argue a borderline fail, but if your borderline anyway then probably the best to reasonably hope for would be a free retake, so barely worth the candle.
    I think most exams try to weed out ambiguous questions, however I recall not being best happy with certain answers I saw from an authorized source material I used for this exam. In fact I think 1z0-147 is a rehash on 1z0-101. In fact I take a right scunner to 1z0-147 and am pleased to see the arrival of 1z0-144 .... Though I half wonder if there's been more interest in 1z0-147 since 1z0-144 arrived :-;
    Rgds- bigdeboy

Maybe you are looking for

  • Changing logical database ADA

    Hi, I have a requirement to change the selection screen of a report. I need to remove one field and add another field in place of it. Now the report selection screen is getting retrieved from logical database ADA. How can I achieve the addition of fi

  • [ADF BC | ADF Faces] Updating a table with values updated in transaction

    Summary: A table is based on a view with a bind variable. Based on some action, I update rows in the view so that they no longer satisfy the query. How do I update the table to reflect this? I have an ADF Faces page with a multi-select table componen

  • Server Config Help

    Hi, We have an application that requires 64-bit linux OS. But I only have this 64-bit laptop for testing. Afaik linux is very hard to install in laptops because of drivers support issue. Is there a laptop brand that is user-friendly to linux? I mean

  • Muvo n200 recognize probl

    i have muvo n200 256mb. i try it on friends comp, it wasnt recognized first,but in other usb port worked fine... when i came home my computer didnt recognized it.. in every usb port.. it says `one of the USB devices attached on copmuter has malfuncti

  • Roxio Toast 8 Titanium help?????

    sorry but i didnt know where else to post this: im trying to use spin doctor to crop and audio file here in the support section: http://kb.roxio.com/content/kb/Toast/000008T it says 'How to define and edit audio tracks with CD Spin Doctor Import trac