我正在從以下VB.NET代碼這個例外只有某些月份:轉換無效
System.InvalidCastException: Conversion from type 'DBNull' to type 'Date' is not valid.
它發生就行了:
If CDate(dRow("CompleteDate")).ToString("d") = arrWeekYear(i, 1).ToString("d") Then
如果我正確理解這個問題,那麼問題是我想比較一些NULL的值爲一個非NULL值的CompleteDate。
我該如何解決這個問題?對於某些日期,上面的代碼完美運行。但是對於一些更新的記錄,事實並非如此。但是我能夠從具有相同日期範圍的T-SQL查詢中獲得輸出,並且沒有錯誤;它也很快運行。我檢查了這個「Date_Completed」和「Review_Date」NULL值的T-SQL查詢,但無論如何,「CompleteDate」總是= NON-Null值。所以我不明白這是怎麼發生的。
這裏是我的VB.NET查詢:
commandstring = "SELECT Batch_Records.Part_Number, Batch_Records.Lot_Number, Batch_Records.Date_Received, " & _
"IsNull([Date_Completed], [Review_Date]) AS [CompleteDate], Batch_Records.Error, " & _
"Batch_Records.[Group], Batch_Records.MFG, Batch_Records.MFG2, Batch_Records.QC, Batch_Records.QC2, " & _
"QC_CODES.CODE_DESC, DATEADD(DD, 1 - DATEPART(DW, Batch_Records.Date_Received), Batch_Records.Date_Received) AS SundayDate " & _
"FROM EXCEL.Batch_Records LEFT JOIN EXCEL.QC_CODES ON Batch_Records.Part_Number = QC_CODES.CODE_ID " & _
"WHERE (Batch_Records.[Group]" & TheGroup & " AND Batch_Records.Date_Received > '" & FirstWeek & "' AND Batch_Records.Date_Received < dateadd(Day, 1, '" & LastWeek & "'))" & _
"ORDER BY Batch_Records.Date_Received"
當我添加了導致錯誤的線高於此線以上,我的報告超時這些個月。那麼該怎麼辦?
If Not dRow("CompleteDate") Is System.DBNull.Value Then
NOOOO!不要使用字符串連接來將值替換爲查詢! **不要這樣做!** –
他是對的,有了這段代碼,你可以很容易地注入sql! – David
在您的查詢中,是「EXCEL」模式,還是您以某種方式加入Excel表單?或者我們只處理SQL? –