我刚刚遇到一个奇怪的问题,我无法检索 sql 存储过程输出参数值。我用了将近 2 个小时来解决这个问题。
代码很简单
using (var con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("sp_mgsearach", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param1 = new SqlParameter("@SearchTerm", SqlDbType.VarChar);
param1.Value = searchTerm;
param1.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("@start", SqlDbType.Int);
param2.Value = start;
param2.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("@end", SqlDbType.Int);
param3.Value = end;
param3.Direction = ParameterDirection.Input;
cmd.Parameters.Add(param3);
SqlParameter param4 = new SqlParameter("@total", SqlDbType.Int);
param4.Direction = ParameterDirection.InputOutput;
param4.Value = 0;
cmd.Parameters.Add(param4);
var reader = cmd.ExecuteReader();
LoadHits(reader);
if (lstHits.Count > 0)
total = Convert.ToInt32(cmd.Parameters["@total"].Value);
else
total = 0;
}
@total 值始终为空。但是当我在查询分析器中执行通过探查器生成的查询时,它返回正常。
最后我发现这是由于 SQL 连接。
如果我在读取输出参数之前关闭连接,它工作正常
LoadHits(reader);
con.close()
if (lstHits.Count > 0)
total = Convert.ToInt32(cmd.Parameters["@total"].Value);
else
total = 0;
WT ..,我只是想不通它为什么会这样..有人知道吗?