以下のコードでは、ロールバックは確実に発生しますが、メソッド 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