0

I have a stored procedure which returns flag values based on certain conditions. The stored procedure does not return a NULL value, it returns 1, 2, or 3 based on some condition. But when I debug, my ADO.NET code throws an exception because ExecuteScalar is returning NULL.

Here is my ADO.NET code:

SqlCommand cmd = new SqlCommand("sp_checkifexists", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name",name);
cmd.Parameters.AddWithValue("@Regno",regno);
cmd.Parameters.Add("@flag", System.Data.SqlDbType.VarChar, 40);
cmd.Parameters["@flag"].Direction = System.Data.ParameterDirection.Output;
con.Open();

// Error occcurs here

int NoOfRows = Convert.ToInt16(cmd.ExecuteScalar());
con.Close();
int flag = (int)cmd.Parameters["@flag"].Value;
return flag;

Any help would be much appreciated!

4

3 回答 3

0

我犯了一个错误

cmd.Parameters.Add("@flag", System.Data.SqlDbType.VarChar, 40);

它是一个整数值,所以它必须是

 cmd.Parameters.Add("@flag", System.Data.SqlDbType.Int);

不管怎么说,多谢拉!

于 2013-09-19T05:51:19.600 回答
0

ExecuteScalar 用于返回具有一行和一列的结果集的存储过程,而不是获取存储过程通过return语句返回的值。所以你必须Select在存储过程中有一个声明。你?

于 2013-09-19T05:35:26.773 回答
0

如果结果是这样,1,2,3那么Convert.ToInt16将失败。你需要有像1

//check what you have return from  `ExecuteScalar` 

var obj = cmd.ExecuteScalar();

if(obj  != DBNull.Value)
{
  //if you have received obj as `1` or `2` etc
  int NoOfRows = Convert.ToInt16(obj) ;
  if you have received obj as `1,2,3`
  List<Int16> valueList = obj.ToString().Split(',').Select(x => Convert.ToInt16(x)).ToList();
}
于 2013-09-19T05:35:50.280 回答