如果我的事业,试图创建一个现有的表的错误,现有的交易似乎已经回滚本身:这是TRANSACTION对我来说是ROLLBACK(ed)吗?
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
,而没有任何问题。
你怎么知道?究竟是什么问题? – Szymon
请参阅代码注释。异常处理程序中的ROLLBACK TRANSACTION失败。 – noelicus
问题是“我不明白”,我想了解发生了什么,为什么。我希望事务回滚是我的责任 - 其他错误对我来说不会这样做。 – noelicus