Use ExecuteScalar
instead of ExecuteReader
and compare against DBNull.Value
.
object result = cmd.ExecuteScalar();
if (result == DBNull.Value)
{
....
}
Вопрос
I need to check if my stored procedure returned null value. Currently I have the following code:
public static bool MyMethod(String isoNum)
{
SqlConnection conn = null;
bool regionExists = true;
try
{
using (conn = new SqlConnection(ConfigurationManager.ConnectionStrings["String"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SPU_GetRegionBasedOnIso", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@isoNum", isoNum);
using (SqlDataReader dr = cmd.ExecuteReader())
{
**<<Here I need to check for NULL value>>**
}
}
}
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
return regionExists;
}
What is the best way to check for NULL here?
Thank you
Решение
Use ExecuteScalar
instead of ExecuteReader
and compare against DBNull.Value
.
object result = cmd.ExecuteScalar();
if (result == DBNull.Value)
{
....
}