3

合計値を取得しようとするクエリがありますが、InvalidCastException が発生します。

私のクエリは次のとおりです。

SELECT e.clockNr,e.firstName,e.LastName,e.unionName,i.points 
FROM ( 
    SELECT employee.clockNr AS clockNr,
           employee.firstName AS firstName,
           employee.lastName AS lastName,
           Unions.name AS unionName 
           FROM employee,Unions 
           WHERE employee.active=1 AND employee.unionId = unions.id  
           GROUP BY employee.clockNr 
     ) e LEFT JOIN (
           SELECT infraction.clockNr AS clockNr, 
           CAST(SUM(Infraction.points) AS SIGNED) AS points 
           FROM infraction 
           WHERE infraction.infractionDate >=@startDate 
           AND infraction.infractionDate <=@endDate 
           GROUP BY infraction.clockNr 
     ) i ON e.clockNr = i.clockNr 
ORDER BY e.clockNr ASC

それがうまくいかないのは「ポイント」列です。CAST を SIGNED に追加しましたが、これは役に立ちません。

私がコラムを読む方法は次のとおりです。

int iGetPoints = Convert.ToInt32(reportReader["points"]);

また試しました:

int iGetPoints = (int)reportReader["points"];

しかし、どちらも InvalidCastException を発生させます。クエリは PHPMyAdmin でテストされ、そこで正常に動作します。

誰かが私が間違っていることを確認したり、どこを探すべきかヒントを教えてくれますか?

4

1 に答える 1

2

列は左結合の一部であるため、pointsnull になる可能性があります。ここが問題だと思います。キャスト例外を回避するには、null をテストする必要があります。

// Note: this is for DataTableReader; see below for MySQL data reader
int iGetPoints = 0;
if (!reportReader.IsDBNull(reportReader.DBOrdinal("points"))) {
   iGetPoints = Convert.ToInt32(reportReader["points"]);
}

このIsDBNullメソッドは列名のインデックスを必要とするため (名前では機能しません)、名前DBOrdinalからインデックスを取得するために を呼び出します。


注:上記の回答は「ジェネリック」System.Data.DataTableReaderクラスでは機能しますが、MySQL データ リーダーでは機能しません。Gerard は、MySQL リーダーに必要な変更を以下のコメントに投稿しました。彼らです:

int iGetPoints = 0;
if (reportReader["points"] != DBNull.Value) {
   iGetPoints = Convert.ToInt32(reportReader["points"]);
}
于 2013-08-08T17:54:50.647 に答える