2013-08-08 13 views
3

합계 값을 가져 오려고하지만 내가 InvalidCastException을 가져 오는 쿼리가 있습니다.C# MySQL InvalidCastException sum

내 쿼리는 다음과 같습니다

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 >[email protected] 
      AND infraction.infractionDate <[email protected] 
      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에서 테스트되었고 제대로 작동합니다.

누구나 내가 잘못하고있는 것을 볼 수 있습니까? 아니면 내게 힌트를 줄 수 있습니까?

+0

'points' 컬럼의 데이터 유형은 무엇입니까 –

+0

INT입니다. 난 그냥 문자열로 구문 분석하려고 다음 int로 변환하고 그 어떤 이유로 작동합니다. –

답변

2

points 열은 왼쪽 조인의 일부이므로 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에 따라서 전화 : 당신은 캐스트 예외를 방지하기 위해 null을 테스트해야합니다 이름에서 색인.


참고 : 위의 답이 아니라 MySQL의 데이터 판독기를 들어, "일반"System.Data.DataTableReader 클래스에 대해 작동합니다. Gerard는 아래 주석에 MySQL 독자에게 필요한 변경 사항을 게시했습니다. 그들은 다음과 같습니다 :

int iGetPoints = 0; 
if (reportReader["points"] != DBNull.Value) { 
    iGetPoints = Convert.ToInt32(reportReader["points"]); 
} 
+0

좋은 점은 MySQL 데이터웨어 하우스 만 DBOrdinal에 익숙하지 않다는 것입니까? –

+0

이것은 트릭을 수행합니다 : int iGetPoints = 0; if (reportReader [ "points"]! = DBNull.Value) { iGetPoints = Convert.ToInt32 (reportReader [ "points"]); } –

+0

감사합니다. Gerard, 좋은 캐치! MySQL 데이터 판독기 용 코드를 포함하도록 내 대답을 업데이트했습니다. 나는 많은 사람들이 그것으로부터 이익을 얻을 것이라고 생각한다. :) –