Rollback at stored procedure vs rollback at C# cod

2019-07-31 23:35发布

I have a procedure Proc1 that calls another procedure Proc2, and both with "BEGIN TRANSCTION" If i get an error at the second procedure, it will rollback both procedures. OK!

But inside my C# code, i have also this

...
   dbCommand.Transaction.Commit();
                dbCnn.Close();
            }
            catch (Exception ex)
            {
                if (dbCommand.Transaction != null)
                    **dbCommand.Transaction.Rollback();**
                if (dbCnn.State == ConnectionState.Open)
                    dbCnn.Close();

                throw ex;
            }

Does "dbCommand.Transaction.Rollback();" knows which transaction I am talking about? And if I have two transactions ate the same procedure, without label, will it be a problem for C# rollback the right transaction?

2条回答
贼婆χ
2楼-- · 2019-08-01 00:01

Does "dbCommand.Transaction.Rollback();" knows which transaction I am talking about?

No. It also does not care. It rolls back the transaction that is wrapping everything on connection level. Everything inside is part of this transaction.

And if I have two transactions ate the same procedure, without label, will it be a problem for C# rollback the right transaction?

You can not have two transactions. Transactions form a hierarchy. The code above rolls back the whole top level connection level transaction. Every other transaction you open in a sstored procedure is part of this transaction.

查看更多
走好不送
3楼-- · 2019-08-01 00:11

As you defined the Transaction in C# code, there is not requirement to add Transaction in SQL Code. if anything goes wrong in SQL Code that will handle by C# Transaction, and rollback otherwise commit.

查看更多
登录 后发表回答