異動和並行存取Transactions and Concurrency

異動是由單一命令或當做封裝 (Package) 執行的命令群組所組成。A transaction consists of a single command or a group of commands that execute as a package. 交易可讓您將多項作業結合成單一工作單位。Transactions allow you to combine multiple operations into a single unit of work. 如果異動的某一處失敗,則所有更新都會復原到異動之前的狀態。If a failure occurs at one point in the transaction, all of the updates can be rolled back to their pre-transaction state.

異動必須符合 ACID 屬性 (單元性 (Atomicity)、一致性 (Consistency)、隔離性 (Isolation) 和持續性 (Durability),才能保證資料一致性。A transaction must conform to the ACID properties—atomicity, consistency, isolation, and durability—in order to guarantee data consistency. 大多數關聯式資料庫系統 (例如 Microsoft SQL Server) 都可以支援異動,其方法是在每次用戶端應用程式執行更新、插入或刪除作業時,提供鎖定、記錄和異動管理功能。Most relational database systems, such as Microsoft SQL Server, support transactions by providing locking, logging, and transaction management facilities whenever a client application performs an update, insert, or delete operation.

注意

如果鎖定保留時間太久,包含多個資源的交易可能會降低並行。Transactions that involve multiple resources can lower concurrency if locks are held too long. 因此,請盡可能縮短異動的時間長度。Therefore, keep transactions as short as possible.

如果某筆異動包含相同資料庫或伺服器中的多個資料表,則預存程序 (Stored Procedure) 中的明確異動通常會有較佳的效能。If a transaction involves multiple tables in the same database or server, then explicit transactions in stored procedures often perform better. 您可以使用 Transact-SQL BEGIN TRANSACTIONCOMMIT TRANSACTIONROLLBACK TRANSACTION 陳述式,在 SQL Server 預存程序中建立交易。You can create transactions in SQL Server stored procedures by using the Transact-SQL BEGIN TRANSACTION, COMMIT TRANSACTION, and ROLLBACK TRANSACTION statements. 如需詳細資訊,請參閱《SQL Server 線上叢書》。For more information, see SQL Server Books Online.

涉及不同資源管理員的交易(例如 SQL Server 與 Oracle 之間的交易)需要分散式交易。Transactions involving different resource managers, such as a transaction between SQL Server and Oracle, require a distributed transaction.

本節內容In This Section

本機異動Local Transactions
示範如何針對資料庫執行交易。Demonstrates how to perform transactions against a database.

分散式異動Distributed Transactions
說明如何在 ADO.NET 中執行分散式異動。Describes how to perform distributed transactions in ADO.NET.

System.Transactions 與 SQL Server 整合System.Transactions Integration with SQL Server
描述System.Transactions如何與使用分散式交易的 SQL Server 整合。Describes System.Transactions integration with SQL Server for working with distributed transactions.

開放式並行存取Optimistic Concurrency
說明開放式與封閉式同步存取,以及如何測試並行違規。Describes optimistic and pessimistic concurrency, and how you can test for concurrency violations.

另請參閱See also