I've got a nested transaction, where after an exception data ends up being in the database without it being committed by the outer transaction.
There are three insert statements, every time followed by an select statement. The second select statement throws the exception. And for some reason I currently can not explain the third statement ends up in the database. If however the exception does not occur (either by removing the select statement or by removing the 0 in the input array) nothing is committed in the database which is the expected behavior.
First of all the small working example:
using (var transactionScope = new TransactionScope())
{
var input = new[] {1, 0, 2 };
foreach (var i in input)
{
using (SqlConnection cnn = new SqlConnection(connetionString))
{
cnn.Open();
using (var tran = cnn.BeginTransaction())
{
var sql = "INSERT INTO [Test].[dbo].[Test] ([Timestamp] ,[Message]) VALUES ('" + DateTime.Now + "', 1 / " + i + ");";
using (SqlCommand cmd = new SqlCommand(sql, cnn, tran))
{
try
{
cmd.ExecuteNonQuery();
tran.Commit();
}
catch (Exception e)
{
tran.Rollback();
}
}
}
}
}
}
What am I missing?
I'm using SQL Server 2016 & C# 7