SqlCommand.ExecuteOnQuery方法与回滚事务
在下面的代码中,肯定会发生回滚,但方法ExecuteOnQuery不会返回-1。 你知道为什么吗SqlCommand.ExecuteOnQuery方法与回滚事务,sql,stored-procedures,executenonquery,Sql,Stored Procedures,Executenonquery,在下面的代码中,肯定会发生回滚,但方法ExecuteOnQuery不会返回-1。 你知道为什么吗 using (var connection = new SqlConnection("")) { connection.Open(); var cmd = connection.CreateCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "SPXpto";
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
}
执行SPXpto 结果:
(1行受影响)
(1行受影响)
(受影响的0行)
1奇怪的相似问题-那是你的同事吗?!是的,我们在同一个地方工作
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;