0

在下面的代码中,回滚肯定会发生,但是 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

4

0 回答 0