查看我继承的一些源代码,有一段代码调用 SQL 存储过程进行更新。
如果出现问题,存储过程返回 -1:
IF @@Error <> 0
BEGIN
ROLLBACK TRAN
SELECT -1
RETURN
END
COMMIT TRAN
SELECT 0
C#代码是这样的:
System.Data.SqlClient.SqlDataReader myReader;
try{
SqlDbConnection.Open();
SqlDbCommand.Connection = SqlDbConnection;
SqlDbCommand.CommandType = System.Data.CommandType.StoredProcedure;
SqlDbCommand.CommandText = "StoredProcedured_UpdateFoo";
SqlDbCommand.Parameters.Clear();
SqlDbCommand.Parameters.Add("@FooData", SqlDbType.DateTime); SqlDbCommand.Parameters["@FooData"].Value = System.DateTime.Now.ToString("yyyy-MM-dd");
myReader = SqlDbCommand.ExecuteReader();
if (myReader.Read())
{
if (int.Parse(myReader.GetValue(0).ToString()) == -1) throw new ErrorDataTxRx("Error FOO ");
}
} finally {
if (SqlDbConnection.State != ConnectionState.Closed){
SqlDbConnection.Close();
}
if (myReader != null){
if (!myReader.IsClosed) myReader.Close();
}
}
我也看到了相同代码的一部分,使用 System.Data.DataSet() 和 Fill 方法检查相同的内容。
有没有更优雅的方法来检查返回值是否为-1?
在这种情况下可以使用 ExecuteReader 吗?
最佳答案
您是否尝试过使用 ExecuteScalar
?这是为返回单个值的查询设计的:
Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored
关于c# - 如何在C#上查看存储过程更新结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3759660/