如果我通过尝试创建现有表导致错误,则现有事务似乎已经自行回滚:
private void CreateSomeThings()
{
SqlConnection SqlConn = new SqlConnection(ConnectionString);
SqlConn.Open();
(new SqlCommand("BEGIN TRANSACTION", SqlConn)).ExecuteNonQuery();
try
{
(new SqlCommand("CREATE TABLE sometable ([some_id] [int] IDENTITY(1,1) NOT NULL)", SqlConn)).ExecuteNonQuery();
// Create the table again, but carry on by catching the exception
try
{
(new SqlCommand("CREATE TABLE sometable ([some_id] [int] IDENTITY(1,1) NOT NULL)", SqlConn)).ExecuteNonQuery();
}
catch (Exception)
{
}
// If another exception is thrown
(new SqlCommand("bingy bongy boo", SqlConn)).ExecuteNonQuery();
(new SqlCommand("COMMIT TRANSACTION", SqlConn)).ExecuteNonQuery();
}
catch (Exception Ex)
{
try
{
// ... then this command will fail with "no corresponding BEGIN TRANSACTION"
(new SqlCommand("ROLLBACK TRANSACTION", SqlConn)).ExecuteNonQuery();
}
catch (Exception Ex2)
{
throw;
}
}
}
我想了解发生了什么以及为什么。我希望事务回滚是我的责任 - 对于其他错误,它不会这样做:例如,如果我只是调用“bingy bongy”,则只有调用引发异常,然后我ROLLBACK
在异常中没有任何问题。