Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assigning the same transaction to multiple commands

Status
Not open for further replies.

JabbaTheNut

Programmer
Jul 29, 2002
176
US
Are there any potential problems with assigning the same transaction to multiple commands? I want to execute a few commands. However, if any one of them fails, I want to rollback everything. The following code illustrates what I want to do (Note that I am assigning the same transaction to both commands):


SqlConnection myConnection = new SqlConnection(myConnString);
myConnection.Open();

SqlCommand myCommand1 = myConnection.CreateCommand();
SqlCommand myCommand2 = myConnection.CreateCommand();
SqlTransaction myTrans;

// Start a local transaction
myTrans = myConnection.BeginTransaction();

// Assign both the transaction object and the connection
// to the Command objects for the pending local transaction
myCommand1.Connection = myConnection;
myCommand1.Transaction = myTrans;

myCommand2.Connection = myConnection;
myCommand2.Transaction = myTrans;

try
{
myCommand1.CommandText = "Do Something";
myCommand1.ExecuteNonQuery();

myCommand2.CommandText = "Do Something Else";
myCommand2.ExecuteNonQuery();

myTrans.Commit();
}
catch(Exception e)
{
myTrans.Rollback();
}
finally
{
myConnection.Close();
}


Game Over, Man!
 
The answer is: It is ok to assign a transaction to multiple commands.

I apologize for asking a question that was easily answered with relatively little research effort. I imagine it was much like my asking: Do you use "open" to open a connection?

Game Over, Man!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top