2014-04-15 2 views
0

null 또는 데이터가있는 단일 레코드를 반환하는 저장 프로 시저가 있습니다.저장 프로 시저에서 Null을 읽는 데 문제가 있습니다.

내 코드에서 프로 시저가 반환하는 내용을 확인해야합니다. 그것을하는 올바른 방법은 무엇입니까?

이제 코드를 실행하면 예외가 발생합니다. "데이터가 없으면 읽을 수 없습니다." 나는 Visual Studio를 여기에 2005

을 사용하고 내 방법 :

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; 
    } 

내가 그것을 해결하기 위해 무엇을 할 수 있는가? 고마워요

답변

1
if (dr.Read()) 
{ 
    if (dr.IsDBNull(0)) 
    { 
     return null; 
    } 
    else 
    { 
     region = (String)dr["region"]; 
    } 
} 
else 
{ 
    // do something else as the result set is empty 
} 
관련 문제