C#でSQL実行時エラーについて
解決したいこと
※コードの再確認は月曜のため、質問への返信が遅くなります。
C#初心者です。
C#からSQLServerを利用して結果を取得しようと考えているのですが、
途中でエラーが出てしまいます。
解決方法をご教示いただければと思います。
発生している問題・エラー
System.OverflowException: 'Conversion overflows.'
Enumeration yielded no results
該当するソースコード
public int getContributions(string strMonth, ref DBColumns.SqlContributions[] sqlContributions)
{
strSQLCon = ConfigurationManager.ConnectionStrings["SQLCon"].ConnectionString;
//Data Source=DB2023;Initial Catalog=TEST;Persist Security Info=True;User ID=test_user;Password=test_user
i = 0;
using (SqlConnection objCon = new SqlConnection(strSQLCon))
using (SqlCommand objCmd = objCon.CreateCommand())
{
try
{
objCon.Open();
SQLContributions = "SELECT CODE, NAME, CLASS, BM_NAME, DATE, TOP_BOTTOM, PRT_NAME, SECTOR, AC_WEIGHT, AV_WEIGHT , CONTRIBUTIONS FROM CONTRIBUTIONS WHERE AC_DATE = yyyymm ORDER BY TOP_BOTTOM DESC,AC_WEIGHT";
SQLContributions = SQLContributions.Replace("yyyymm", strMonth); //strMonthは当月
objCmd.CommandText = SQLContributions;
using (SqlDataReader objReader = objCmd.ExecuteReader())
{
while (objReader.Read())
{
sqlContributions[i] = new DBColumns.SqlContributions();
sqlContributions[i].CODE = (string)objReader.GetValue(0);
sqlContributions[i].NAME = (string)objReader.GetValue(1);
sqlContributions[i].CLASS = (string)objReader.GetValue(2);
sqlContributions[i].BM_NAME = (string)objReader.GetValue(3);
sqlContributions[i].DATE = (int)objReader.GetValue(4);
sqlContributions[i].TOP_BOTTOM = (string)objReader.GetValue(5);
sqlContributions[i].PRT_NAME = (string)objReader.GetValue(6);
sqlContributions[i].SECTOR = (string)objReader.GetValue(7);
sqlContributions[i].AC_WEIGHT = (decimal)objReader.GetValue(8);
sqlContributions[i].AV_WEIGHT = (decimal)objReader.GetValue(9);
sqlContributions[i].CONTRIBUTIONS = (decimal)objReader.GetValue(10);
//最後のobjReader.GetValue(10)でエラー。
//列番号ではなく列名に変更しても同様のエラー。
i++;
Array.Resize(ref sqlContributions, i + 1);
}
}
DataBottom = i;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw;
}
finally
{
objCon.Close();
}
}
return DataBottom;
}
自分で試したこと
Classで生成した変数にそれぞれ入れていて、そこの型はSQLと完全に同じ型で作成しております。
元々、以下のコードで試していましたが、以下のコードの場合NULL判断のところでエラーが出ます。
if (objReader["CONTRIBUTIONS"] != DBNull.Value) {
sqlContributions[i].CONTRIBUTIONS = (decimal)objReader[10];
}
初歩的な質問で申し訳ございませんが、
探しても回答を見つけられなかったため、何卒よろしくお願いいたします。