tailieunhanh - Microsoft SQL Server 2005 Developer’s Guide- P11

Microsoft SQL Server 2005 Developer’s Guide- P11:This book is the successor to the SQL Server 2000 Developer’s Guide, which was extremely successful thanks to all of the supportive SQL Server developers who bought that edition of the book. Our first thanks go to all of the people who encouraged us to write another book about Microsoft’s incredible new relational database server: SQL Server 2005. | Chapter 6 Developing Database Applications with 199 functions would be considered part of the same logical transaction. From the database standpoint to ensure database integrity both the withdrawal and the deposit would be grouped together as a single transaction. If the withdrawal operation succeeded but the deposit failed the entire transaction could be rolled back which would restore the database to the condition it had before the withdrawal operation was attempted. Using transactions is an essential part of most production-level database applications. supports transactions using the Transaction classes. In order to incorporate transactions into your applications you first need to create an instance of the SqlTransaction object and then execute the BeginTransaction method to mark the beginning of a transaction. Under the covers this will cause the database server to begin a transaction. For instance using the SqlTransaction object to issue a BeginTransaction statement will send a T-SQL BEGIN TRANSACTION command to SQL Server. After the transaction has started the database update operations are performed and then the Commit method is used to actually write the updates to the target database. If an error occurs during the process then the RollBack operation is used to undo the changes. The following SQLCommandTransaction subroutine shows how to start a transaction and then either commit the results of the transaction to the database or roll back the transaction in the event of an error Private Sub SQLCommandTransaction cn As SqlConnection Dim cmd As New SqlCommand Dim trans As SqlTransaction Start a local transaction trans cn trans Try Insert a row transaction _ INSERT INTO Department VALUES 100 Transaction 100 This next insert will result in an error _ INSERT INTO Department VALUES 100 Transaction 101 .