SQL Server Transactions 事务

事务这一概念的提出是为了处理某些情况,在这些情况中数据库的结果状态取决于一系列操作是否全部成功。之所以这样,是因为后面的操作可能会修改先前操作的结果。在这些情况下,如果任意一个操作失败,结果状态将不确定。

为解决这一问题,事务以一种最终结果的完整性可以得到保障的方式将系列操作进行分组。或者所有的操作必须成功,然后提交(写入数据库),或者整个事务失败。取消事务称为回滚。回滚允许恢复所做的更改,将数据库返回至事务前状态。

例如,在一次自动银行事务中,如果将一笔款从 A 帐户转入 B 帐户,则从 A 帐户取款和存入 B 帐户都必须成功才能正确处理该笔款项,否则整个事务必定失败。

事务必须具有 ACID 属性,它代表以下意思:

  • 原子性   事务是工作的原子单元,它的执行是一次性的,要么所有工作都完成,要么都没有完成。

  • 一致性   事务保持数据的一致性,把数据的一种一致状态转换为另一种一致状态。必须在语义上保留事务绑定的数据。

  • 隔离   事务是一个隔离单元,并发事务中的每个事务在发生时都相互分离,彼此独立。一个事务决不应看到另一事务的中间阶段。

  • 持久性   事务是一个恢复单元。如果事务成功,其更新就保持,即使系统发生故障或者关闭也如此。如果事务失败,则系统保持提交该事务前的状态。

http://msdn2.microsoft.com/zh-cn/library/tyes10w5(VS.80).aspx

Transactions 

The concept of a transaction was developed to handle cases in which the resulting state of the database depends on the total success of a series of operations. This could come about because successive operations might modify the results of previous operations. In such cases, if any one operation fails, the resulting state could be indeterminate.

To solve this problem, transactions group a series of operations in such a way that the integrity of the final result can be assured. Either all the operations must succeed and then be committed (written to the database) or the entire transaction fails. The cancellation of the transaction is called a rollback. Rollback allows a recovery from the changes and returns the database to the pretransaction state.

For example, in an automated banking transaction, if you transfer money from account A to account B, both the withdrawal from A and the deposit to B must succeed to process the funds correctly, or the whole transaction must fail.

A transaction must have ACID properties, which stand for the following:

  • Atomicity   A transaction is an atomic unit of work and executes exactly once; either all the work is done or none of it is.

  • Consistency   A transaction preserves the consistency of data, transforming one consistent state of data into another consistent state of data. Data bound by a transaction must be semantically preserved.

  • Isolation   A transaction is a unit of isolation and each occurs separately and independently of concurrent transactions. A transaction should never see the intermediate stages of another transaction.

  • Durability   A transaction is a unit of recovery. If a transaction succeeds, its updates persist, even if the system crashes or is shut down. If a transaction fails, the system remains in the state previous to committing the transaction.

http://msdn2.microsoft.com/en-us/library/tyes10w5(VS.80).aspx

posted @ 2007-10-31 14:34  许晓光  阅读(315)  评论(0编辑  收藏  举报