C# 读取存储过程返回的null时遇到问题
我有一个存储过程,它返回单个记录,C# 读取存储过程返回的null时遇到问题,c#,sql,stored-procedures,null,visual-studio-2005,C#,Sql,Stored Procedures,Null,Visual Studio 2005,我有一个存储过程,它返回单个记录,null或数据(如果存在) 在我的代码中,我需要检查该过程返回的内容。正确的方法是什么 现在,在运行代码时,我遇到了一个异常:“在没有数据存在的情况下尝试读取无效。”我使用的是VisualStudio2005 以下是我的方法: public static String GetRegionBasedOnIso(String isoNum) { SqlConnection conn = new SqlConnection(Configurat
null
或数据(如果存在)
在我的代码中,我需要检查该过程返回的内容。正确的方法是什么
现在,在运行代码时,我遇到了一个异常:“在没有数据存在的情况下尝试读取无效。”我使用的是VisualStudio2005
以下是我的方法:
public static String GetRegionBasedOnIso(String isoNum)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConn"].ConnectionString);
String region = null;
try
{
using (SqlCommand cmd = new SqlCommand("MyProc", conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@isoNum", isoNum);
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.IsDBNull(0))
{
return null;
}
else
{
region = (String)dr["region"];
}
}
}
}
catch (Exception e)
{
throw new System.Exception(e.Message.ToString());
}
finally
{
conn.Close();
}
return region;
}
我能做些什么来修复它?多谢各位
if (dr.Read())
{
if (dr.IsDBNull(0))
{
return null;
}
else
{
region = (String)dr["region"];
}
}
else
{
// do something else as the result set is empty
}