在下面的代码中,确实会发生回滚,但是ExecuteNonQuery方法没有返回-1。 有什么想法吗?
using (var connection = new SqlConnection(""))
{
connection.Open();
var cmd = connection.CreateCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "SPXpto";
var res = cmd.ExecuteNonQuery();
System.Console.WriteLine(res);// prints 2: number of rows affected in the SP
}
BEGIN TRANSACTION
BEGIN TRY
UPDATE table_xpto SET xpto = 1 WHERE xpto2= 1; -- OK
UPDATE table_xpto SET xpto = 1 WHERE xpto2= 1; -- OK
UPDATE table_xpto SET xpto = 1 WHERE xpto2 = 'x'; -- ERROR ON PURPOSE: "Conversion failed when converting the varchar value 'x' to data type int."
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
PRINT ERROR_STATE();
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
执行SPXpto;
结果:
(1行受影响)
(1行受影响)
(0行受影响)
1