Sunday, October 12, 2008

Transactions on multiple calls to the database


Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim tran As SqlTransaction
' Create a New Connection
conn = New SqlConnection("ConnString")
' Open the Connection
conn.Open()
' Create a new Command object
cmd = New SqlCommand()
' Create a new Transaction
tran = conn.BeginTransaction
' Set the Transaction within which the Commands execute
cmd.Transaction = tran
Try
' Insert the Order header
' Set the Command properties
With cmd
.CommandType = CommandType.StoredProcedure
.CommandText = "InsertOrderHeader"
.Connection = conn
' Add input and output parameters
.Parameters.Add("@CustomerId", SqlDbType.Int)
.Parameters("@CustomerId").Direction = ParameterDirection.Input

' Set the parameter values
.Parameters("@CustomerId").Value = 1

' Execute the command
.ExecuteNonQuery()
' Get the OrderId of the newly selected order header
OrderId = .Parameters("@OrderId").Value
' Clear the parameters for the next command
.Parameters.clear()
End With

' Insert the Order Details
' Set Command properties
With cmd
.CommandType = CommandType.StoredProcedure
.CommandText = "InsertOrderDetail"
.Connection = conn
' Add parameters
.Parameters.Add("@OrderId", SqlDbType.Int)
.Parameters("@OrderId").SourceColumn = "OrderId"
.Parameters("@OrderId").Direction = ParameterDirection.Input

' Set the parameter values
.Parameters("@OrderId").Value = OrderId
.Parameters("@ItemId").Value = 100

' Execute the command
.ExecuteNonQuery()
' Repeat the above few lines for each order detail
End With

' Commit the Transaction
tran.Commit()
Catch
' Rollback the Transaction
tran.Rollback()
Finally
' Cleanup Code
' Close the Connection
conn.Close()
End Try

No comments: