2016-10-30 2 views
1

나는 각 고객 (총 인보이스)을 계산하기 위해 아래의 코드를 사용했습니다. 고객에게는 인보이스가 없습니다. 오류를 반환합니다. null로 오류를 처리하려고했지만 작동하지 않습니다.ExecuteScalar() 반환 오류 "지정된 캐스트가 유효하지 않습니다." 레코드가 없을 때

public static decimal GetInvoiceTotal(int customerID) 
    { 
     SqlConnection connection = MMABooksDB.GetConnection(); 
     string selectStatement 
      = "SELECT SUM(InvoiceTotal) " 
      + "FROM Invoices " 
      + "WHERE CustomerID = @CustomerID"; 
     SqlCommand selectCommand = 
      new SqlCommand(selectStatement, connection); 
     selectCommand.Parameters.AddWithValue("@CustomerID", customerID); 




     try 
     { 
      connection.Open(); 

      if (selectCommand.ExecuteScalar()!=null) 
      { 
       decimal invoiceTotal = (decimal)selectCommand.ExecuteScalar(); 
       return invoiceTotal; 
      } 


      else 
      { 
       return 0; 
      } 
     } 
     catch (SqlException ex) 
     { 
      throw ex; 
     } 
     finally 
     { 
      connection.Close(); 
     } 
    } 
+0

10 진수로 변환하는 이유가 있습니까? 또한 ExecuteScalar를 한 번만 사용하도록 코드를 수정해야합니다. –

+0

http://stackoverflow.com/questions/1999020/handling-executescalar-when-no-results-are-returned – TheRealVira

답변

2

ExecuteScalar 번으로 전화 할 필요가 없습니다. 넓은 스트로크에서

var value = selectCommand.ExecuteScalar(); 
if(value != DBNull.Value) 
{ 
    return (decimal)value; 
} 

업데이트

DBNull 클래스가 아닌 기존의 값을 나타냅니다. null과 다른 점은 객체에 대한 참조가 없음을 의미합니다. 따라서 SQL 쿼리 결과가 NULL 인 경우 ADO.NET (데이터베이스에 액세스하는 데 사용 된 기술) 값이 DBNull입니다.

자세한 내용은 here을 참조하십시오.

+0

당신의 대답처럼 내 코드가 바뀌 었습니다. 디버그로 확인했습니다. var 값은 {}이고 조건을 전달합니다. if value! = null), (value! = null) – Masoud

+0

아직 작동하지 않는 경우, 나는 값 = {} 일 때 의미를 모르며 null이 아닌 경우 어떻게 전달되는지 모르겠다. – Masoud

+0

@Masoud 디버깅을 위해 return 문 앞에 'var temp = value.ToString();'문을 추가하고'temp'의 값을 알려주십시오. 감사합니다 – Christos