Question

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

Was it helpful?

Solution

Use ExecuteScalar instead of ExecuteReader and compare against DBNull.Value.

object result = cmd.ExecuteScalar();
if (result == DBNull.Value)
{
    ....
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top