나는 각 고객 (총 인보이스)을 계산하기 위해 아래의 코드를 사용했습니다. 고객에게는 인보이스가 없습니다. 오류를 반환합니다. 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();
}
}
10 진수로 변환하는 이유가 있습니까? 또한 ExecuteScalar를 한 번만 사용하도록 코드를 수정해야합니다. –
http://stackoverflow.com/questions/1999020/handling-executescalar-when-no-results-are-returned – TheRealVira