You are on page 1of 2

Overview of Transactions

Managing Transactions
Example A The following code example shows how to name a transaction. USE AdventureWorks ; DECLARE @TranName VARCHAR(20) SELECT @TranName = 'MyTransaction' BEGIN TRANSACTION @TranName GO DELETE FROM AdventureWorks.HumanResources.JobCandidate WHERE JobCandidateID = 13 GO COMMIT TRANSACTION MyTransaction The following is the message displayed for the query. 1 row is affected. Example B The following code example shows how to mark a transaction with a specified name in the log. USE AdventureWorks ; BEGIN TRANSACTION CandidateDelete WITH MARK N'CandidateDelete' GO DELETE FROM AdventureWorks.HumanResources.JobCandidate WHERE JobCandidateID = 13 GO COMMIT TRANSACTION CandidateDelete GO The following is the message displayed for the query. 1 row is affected. Example C The following code example creates an explicit transaction and performs a couple of DML operations on the JobCandidate table. USE AdventureWorks ; BEGIN TRANSACTION GO UPDATE HumanResources.JobCandidate SET EmployeeID = 9 WHERE JobCandidateID = 1 DELETE FROM HumanResources.JobCandidate WHERE JobCandidateID = 13 GO COMMIT TRANSACTION The following is the message displayed for the query. 1 row is affected. 0 row(s) are affected. Example D

The following code example creates an explicit transaction, performs a DML operation, and shows how a ROLLBACK transaction nullifies the delete operation. BEGIN TRANSACTION GO SELECT * FROM HumanResources.JobCandidate WHERE JobCandidateID = 12 GO DELETE FROM HumanResources.JobCandidate WHERE JobCandidateID = 12 GO SELECT * FROM HumanResources.JobCandidate WHERE JobCandidateID = 12 GO ROLLBACK SELECT * FROM HumanResources.JobCandidate WHERE JobCandidateID = 12 GO The following is the message displayed for the query. 1 row is affected. 0 row(s) are affected.

JobCandidateID 12 9

EmployeeID

The following is the message displayed for the query. 1 row is affected. 1 row is affected. 0 row(s) are affected. The following is the partial result set of the query. JobCandidateID 12 9 EmployeeID

The following is the message displayed for the query. 1 row is affected.

You might also like