`
danwind
  • 浏览: 232795 次
  • 性别: Icon_minigender_1
  • 来自: 广东
社区版块
存档分类
最新评论

Oracle自治事务pragma autonomous_transaction的介绍

 
阅读更多

transaction has no link to the calling transaction, so only commited data can be shared by both transactions.
自治事务允许你离开调用的事务上下文,执行一个独立的事务,然后返回调用的事务而不会影响到调用事务的状态。自治事务和调用事务不同,只有提交的事务才会在事务见共享。


The following types of PL/SQL blocks can be defined as autonomous transactions:
以下的PL/SQL代码块可以定义为自治事务。

    * Stored procedures and functions. 存储过程和函数
    * Local procedures and functions defined in a PL/SQL declaration block. 定义在声明块里的本地存储过程和函数
    * Packaged procedures and functions. 打包的存储过程和函数
    * Type methods. 类型方法
    * Top-level anonymous blocks. 顶层的匿名块

The easiest way to understand autonomous transactions is to see them in action. To do this, we create a test table and populate it with two rows. Notice that the data is not commited.
最简单的理解自治事务的方法是查看他们的行为。我们创建一个测试表格,然后放入2行数据,注意数据没有提交。


    CREATE TABLE at_test (
      id NUMBER NOT NULL,
      description VARCHAR2(50) NOT NULL
    );

    INSERT INTO at_test (id, description) VALUES (1, 'Description for 1');
    INSERT INTO at_test (id, description) VALUES (2, 'Description for 2');

    SELECT * FROM at_test;

            ID DESCRIPTION
    ---------- --------------------------------------------------
             1 Description for 1
             2 Description for 2

    2 rows selected.

    SQL>

Next, we insert another 8 rows using an anonymous block declared as an autonomous transaction, which contains a commit statement.
下一步,我们使用匿名的自治事务块插入另外8行数据,同时提交。

    DECLARE
      PRAGMA AUTONOMOUS_TRANSACTION;
    BEGIN
      FOR i IN 3 .. 10 LOOP
        INSERT INTO at_test (id, description)
        VALUES (i, 'Description for ' || i);
      END LOOP;
      COMMIT;
    END;
    /

    PL/SQL procedure successfully completed.

    SELECT * FROM at_test;

            ID DESCRIPTION
    ---------- --------------------------------------------------
             1 Description for 1
             2 Description for 2
             3 Description for 3
             4 Description for 4
             5 Description for 5
             6 Description for 6
             7 Description for 7
             8 Description for 8
             9 Description for 9
            10 Description for 10

    10 rows selected.

    SQL>

As expected, we now have 10 rows in the table. If we now issue a rollback statement we get the following result.
和预想的一样,我们得到了10行数据。如果我们执行一个回滚(rollback)语句,我们得到了如下的结果

    ROLLBACK;
    SELECT * FROM at_test;

            ID DESCRIPTION
    ---------- --------------------------------------------------
             3 Description for 3
             4 Description for 4
             5 Description for 5
             6 Description for 6
             7 Description for 7
             8 Description for 8
             9 Description for 9
            10 Description for 10

    8 rows selected.

    SQL>

The 2 rows inserted by our current session (transaction) have been rolled back, while the rows inserted by the autonomous transactions remain. The presence of the PRAGMA AUTONOMOUS_TRANSACTION compiler directive made the anonymous block run in its own transaction, so the internal commit statement did not affect the calling session. As a result rollback was still able to affect the DML issued by the current statement.
被我们当前事务插入的2行数据被回滚了,而被自治事务插入的数据继续存在。编译描述符 PRAGMA AUTONOMOUS_TRANSACTION 使得自治块在自己的事务里运行,所以内部的提交语句不会影响调用方的事务。

Autonomous transactions are commonly used by error logging routines, where the error messages must be preserved, regardless of the the commit/rollback status of the transaction. For example, the following table holds basic error messages.
自治事务一般用于日常的错误日志,错误信息必须保留,无论事务是提交还是回滚。例如下面的表保存了基本的错误信息。

    CREATE TABLE error_logs (
      id NUMBER(10) NOT NULL,
      log_timestamp TIMESTAMP NOT NULL,
      error_message VARCHAR2(4000),
      CONSTRAINT error_logs_pk PRIMARY KEY (id)
    );

    CREATE SEQUENCE error_logs_seq;

We define a procedure to log error messages as an autonomous transaction.
我们定义了一个自治事务的存储过程来记录错误信息

    CREATE OR REPLACE PROCEDURE log_errors (p_error_message IN VARCHAR2) AS
      PRAGMA AUTONOMOUS_TRANSACTION;
    BEGIN
      INSERT INTO error_logs (id, log_timestamp, error_message)
      VALUES (error_logs_seq.NEXTVAL, SYSTIMESTAMP, p_error_message);
      COMMIT;
    END;
    /

The following code forces an error, which is trapped and logged.
下面的代码强制产生一个错误,被捕获且记录到日志

    BEGIN
      INSERT INTO at_test (id, description)
      VALUES (998, 'Description for 998');

      -- Force invalid insert.
      INSERT INTO at_test (id, description)
      VALUES (999, NULL);
    EXCEPTION
      WHEN OTHERS THEN
        log_errors (p_error_message => SQLERRM);
        ROLLBACK;
    END;
    /

    PL/SQL procedure successfully completed.

    SELECT * FROM at_test WHERE id >= 998;

    no rows selected

    SELECT * FROM error_logs;

            ID LOG_TIMESTAMP
    ---------- ---------------------------------------------------------------------------
    ERROR_MESSAGE
    ----------------------------------------------------------------------------------------------------
             1 28-FEB-2006 11:10:10.107625
    ORA-01400: cannot insert NULL into ("TIM_HALL"."AT_TEST"."DESCRIPTION")


    1 row selected.

    SQL>

From this we can see that the LOG_ERRORS transaction was separate to the anonymous block. If it weren't, we would expect the first insert in the anonymous block to be preserved by the commit statement in the LOG_ERRORS procedure.
由此可知,LOG_ERRORS事务被分割为自治块。如果不是,我们可以期待在自治块插入的第一个数据被LOG_ERRORS存储过程的提交语句后保留。

Be careful how you use autonomous transactions. If they are used indiscriminately they can lead to deadlocks, and cause confusion when analyzing session trace. To hammer this point home, here's a quote from Tom Kyte posted on my blog (here):
小心你使用自治存储过程的方式。如果你胡乱使用,可能会引起死锁,同时在分析跟踪事务时引起冲突。下面是Tom Kyte在我的博客里提供的一些建议:

    ... in 999 times out of 1000, if you find yourself "forced" to use an autonomous transaction - it likely means you have a serious data integrity issue you haven't thought about.


    Where do people try to use them?

        * in that trigger that calls a procedure that commits (not an error logging routine). Ouch, that has to hurt when you rollback.
        * in that trigger that is getting the mutating table constraint. Ouch, that hurts *even more*

    Error logging - OK.

    Almost everything else - not OK.
文章出处:飞诺网(www.diybl.com):http://www.diybl.com/course/7_databases/oracle/oraclejs/200919/154466.html

分享到:
评论

相关推荐

    Oracle自治事务的介绍(Autonomous_Transactions)

    Oracle自治事务的介绍(Autonomous_Transactions) Oracle自治事务是一种特殊的数据库事务机制,允许在调用事务的上下文中执行独立的事务。这种机制使用PRAGMA_AUTONOMOUS_TRANSACTION语句来定义自治事务。自治事务...

    oracle自治事务(Trigger)

    ### Oracle自治事务(Trigger)详解 #### 一、概述 Oracle数据库中的触发器是一种存储过程,它被设计为当特定事件发生时自动执行。这些事件包括数据修改操作,如INSERT、UPDATE或DELETE等。触发器可以确保数据的...

    Oracle数据完整性嵌套事务调用分析研究

    在 Oracle 中,我们可以使用 PRAGMA AUTONOMOUS_TRANSACTION 语句来声明自治事务。 例如,在Proc_SaveBill存储过程中,我们可以使用自治事务来生成单据编号: ```sql CREATE OR REPLACE PROCEDURE Proc_SaveBill AS...

    Oracle中怎样用自治事务保存日志表

    要创建一个自治事务,您必须在匿名块的最高层或者存储过程、函数、数据包或触发的定义部分中,使用PL/SQL中的PRAGMA AUTONOMOUS_TRANSACTION语句。在这样的模块或过程中执行的SQL Server语句都是自治的。

    oracle触发器调用存储过程

    Oracle自治事务(Autonomous Transaction)机制可以解决这个问题,确保触发器和存储过程之间的事务独立性。 触发器调用存储过程的过程中可能会出现的问题是,insert语句不是自动提交的,因此当insert语句没有提交时...

    事务与锁定的问题 自治事务

    在这个例子中,`log_msg`过程使用了`PRAGMA AUTONOMOUS_TRANSACTION`指令,使其成为自治事务,即使主事务失败,日志记录也能成功提交。 #### 结论 事务和锁定是数据库管理中至关重要的概念,它们不仅保证了数据的...

    oracle开发常用知识

    为了声明一个存储过程或函数为自治事务,需要使用`Pragma Autonomous_Transaction`关键字。此声明意味着该存储过程中执行的操作将是独立的,不受外部事务状态的影响。例如: ```sql CREATE OR REPLACE PROCEDURE ...

    oracle sql项目开发中常见问题总结

    自治事务通过`PRAGMA AUTONOMOUS_TRANSACTION`来声明。在一个自治事务中,即使外部事务回滚,自治事务中的更改也会提交。例如: ```sql FUNCTION Get_SerialNo(i_SerialType NUMBER) RETURN VARCHAR2 IS PRAGMA ...

    oracle之sqlFAQ

    使用 `PRAGMA AUTONOMOUS_TRANSACTION` 可以创建自治事务,确保过程内部的事务不影响外部事务。例如: ```sql FUNCTION Get_SerialNo(i_SerialType NUMBER) RETURN VARCHAR2 IS PRAGMA AUTONOMOUS_TRANSACTION; ...

    富士通内部培训ORACLE资料

    使用`PRAGMA AUTONOMOUS_TRANSACTION`开启自治事务。 13. **在过程中暂停指定时间**:可以使用`DBMS_LOCK.SLEEP`过程来暂停PL/SQL代码的执行,参数为睡眠的秒数。 14. **计算事务时间和日志量**:事务时间可以通过...

    oracle

    使用`PRAGMA AUTONOMOUS_TRANSACTION`声明一个过程或函数为自治事务。 ### 6. 变量与参数 PL/SQL中变量和参数的使用至关重要,用于存储和传递数据。变量可以通过`VARIABLE_NAME := expression;`进行赋值,参数则在...

    oracle学习笔记

    通过在存储过程声明`PRAGMA AUTONOMOUS_TRANSACTION`,可以确保事务独立于外部事务进行提交或回滚。 2. 包(Package):包是PL/SQL的高级特性,包括包说明(Specification)和包体(Body)。包说明定义了包的公共...

    oracle chm帮助文件下载

    12. **自治事务**:在PL/SQL块中,可以使用`PRAGMA AUTONOMOUS_TRANSACTION`声明一个自治事务,该事务独立于外部事务,可以在完成后立即提交或回滚。 13. **暂停指定时间**:`DBMS_LOCK.SLEEP`函数可以在PL/SQL中...

Global site tag (gtag.js) - Google Analytics