Solved

Transaction Rollback and Commit

Posted on 2014-10-29
1
166 Views
Last Modified: 2014-10-30
Please help me to understand Rollback/Commit using the following example:

Q1. Line 20: Rollback       <-- by default it rolls back to the previous Begin Tran AddCustomer (at line 11)
                                                   (There is no need to use Rollback Tran AddCustomer, is this correct?)

I have 3 named Transactions AddCustomer (at line 11),  AddAnOrderTo_tblOrders (at line 31), and AddTitleTotblIrderDetails (at line 49)

Q2. If any of the 3 transactions fail, all transaction need to be rolled back. Where do I put my commits Tran ???.

Q3: Will Else Block with 3 commits (see line 64) do the job?

BEGIN

--SET NOCOUNT ON;

Declare @CustID int
Declare @OrderID int
Declare @AddedOrderCount int = 0
Declare @AddedCustomerCount int = 0
Declare @msg varchar(100)=''

BEGIN TRAN AddCustomer --*  *  *  *  *  *  *  *  *  *  *  *  *  T-1

	Insert Into tblCustomers(FirstName, LastName, [Address], City, [State], ZipCode, Phone, Email)
					Values(@FirstName, @LastName, @Address, @City, @State, @ZipCode, @Phone, @Email)

	-- Rollback the transaction if there were any errors
	IF @@ERROR <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK

			-- Raise an error and return
			RAISERROR ('Error adding customer to tblCustomers.', 16, 1)
			RETURN @@ERROR
		END --*  *  *  *  *  *  *  *  *  *   *  *  *  *  *  *   *  *  *  *  * T-1
	
Set @CustID = SCOPE_IDENTITY()
Set @AddedCustomerCount = @@ROWCOUNT


BEGIN TRAN AddAnOrderTo_tblOrders -- *  *   *  *  *  *  *  *  T-2
   
	Insert Into tblOrders (CustomerID, OrderDate)
						 Values(@CustID,GETDATE())
						   
	-- Rollback the transaction if there were any errors
	IF @@ERROR <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK AddCustomer

			-- Raise an error and return
			RAISERROR ('Adding customer with an order failed (Error occured when adding order to tblOrders).', 16, 1)
			RETURN @@ERROR
		END --*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *   *  *  *   *  *  * T-2	
			
		Set @OrderID = SCOPE_IDENTITY()

	BEGIN TRAN AddTitleTotblIrderDetails --*  *   *  T-3
		
	Insert Into tblOrderDetails(OrderID, SoftwareID, Quantity)
					   Values(@OrderID, @SoftwareID, @Quantity) 
						 
	-- Rollback the transaction if there were any errors
	IF @@ERROR <> 0
		BEGIN
			-- Rollback the transaction
			ROLLBACK AddCustomer

			-- Raise an error and return
			RAISERROR ('Adding customer with an order failed (Error occurred when adding order item to tblOrderDetails).', 16, 1)
			RETURN @@ERROR
		END --*  *  *  *  *  *  *  *  *  *  *  *  *  *  *  *   *  *  *   *  *  * T-3
	Else
	    BEGIN
		COMMIT TRAN AddCustomer -- *   *  *  *  *  *   *   *  * T-1
		COMMIT TRAN AddAnOrderTo_tblOrders -- *   *  *  *  *  * T-2
		COMMIT TRAN AddTitleTotblIrderDetails -- *   *    *   * T-3		
	    END	
End

Set @AddedOrderCount = @@ROWCOUNT

Set @msg ='Customers added: ' + CAST(@AddedCustomerCount AS NVARCHAR(10)) +
              '; Orders added: ' + CAST(@AddedOrderCount AS NVARCHAR(10));

if @@Error>0 
     Set @msg = @msg + '; SQL Server error: ' + CAST(@@Error AS NVARCHAR(10))

Set @message = @msg

Return @@Error

END 

Open in new window

0
Comment
Question by:Mike Eghtebas
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
1 Comment
 
LVL 13

Accepted Solution

by:
Koen Van Wielink earned 500 total points
ID: 40412942
This might be a silly question, but if you want all 3 transactions to roll back if any one of them fails, why do you separate it into three transactions? Why not just use a single transaction?
0

Featured Post

PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Using examples as well as descriptions, and references to Books Online, show the different Recovery Models available in SQL Server and explain, as well as show how full, differential and transaction log backups are performed
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

631 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question