views:

637

answers:

1

Hi All,
I am having a slight issue. Please guide me. I am coding in C#(Console App). I have called 2 different stored procedure in my code. Basically both these stored procedures access the same table. First SP has a select query and an update query. Second SP has a single update query.

Now I want to call these SP in a transaction mode(Either all succeeds or is second SP fails rollback first SP). I have used "TransactionScope" within my C# code but is doesnt seem to work fine. ie when I stop the Console App sometimes I see that the first SP is executed and the second one fails.

Can anybody suggest me on this.

Regards,
Justin Samuel.

+2  A: 

If you are using TransactionScope, it should work fine, but the scope must surround the connection(s):

using(TransactionScope tran = new TransactionScope()) {
    using(SqlConnection conn = new SqlConnection(cs)) {
      // either multiple commands on one connection
      using(SqlCommand cmd = conn.CreateCommand()) {
        // etc
      }
      using(SqlCommand cmd = conn.CreateCommand()) {
        // etc
      }
    }
    using(SqlConnection conn = new SqlConnection(cs)) {
      // or a separate connection
      using(SqlCommand cmd = conn.CreateCommand()) {
        // etc
      }
    }
    tran.Complete();
}

There is an edge case where a TransactionScope can fail causing the later command to run without a transaction.

Alternatively, for a single connection use SqlTransaction, but remember to associate the transaction (from the connection) to each command.

Marc Gravell
Marc,I am bit confused. I am fetching one row at a time. Doin some processing using the two SPs. This individual row processing is in a TransactionScope. If I write SqlConnection within each Transaction it would mean separate connection in each transaction.Please suggest if I am wrong!
Justin
Sorry, I got called away - will update.
Marc Gravell
Finally, I had to create a separate connection within each transaction.Excellent Marc!!!Thanks Marc and Goran for the support.Cheers!!!
Justin
Sounds like you are blocking yourself due to serializable isolation level.
Marc Gravell
Marc, I working perfectly fine with two instance of Console opened. and the transaction works just smoothly.However when I open a third Console App, i just timesOut. Need to investigate this! :)
Justin