0

In code bellow the rollback occurs for sure, but the method ExecuteNonQuery doesn´t return -1 has expected. Any ideas why?

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;  

execute SPXpto;

Result:
(1 row(s) affected)
(1 row(s) affected)
(0 row(s) affected)
1

jophab
  • 5,356
  • 14
  • 41
  • 60

0 Answers0