私は各顧客(合計請求書)を計算するために以下のコードを使用しました。顧客には請求書がありません。エラーを返します。ヌルでエラーを処理しようとしましたが動作しません。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を1回だけ使用するようにコードを変更する必要があります。 –
http://stackoverflow.com/questions/1999020/handling-executescalar-when-no-results-are-returned – TheRealVira