从类型' DBNull'的转换键入' Date'无效的 [英] Conversion from type 'DBNull' to type 'Date' is not valid

查看:104
本文介绍了从类型' DBNull'的转换键入' Date'无效的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅在某些月份内,我从以下VB.NET代码中获得了此异常:

I am getting this exception from the following VB.NET code for only certain months:

System.InvalidCastException: Conversion from type 'DBNull' to type 'Date' is not valid.

它发生在行上:

If CDate(dRow("CompleteDate")).ToString("d") = arrWeekYear(i, 1).ToString("d") Then

如果我正确理解这一点,那么问题是我正在尝试将CompleteDate的一些NULL值与非NULL值进行比较.

If I understand this correctly, then the problem is I am trying to compare some NULL values for CompleteDate to a non-NULL value.

我该如何解决?对于某些日期,上面的这段代码可以完美运行.但是,对于一些较新的记录,事实并非如此.但是我可以从具有相同日期范围的T-SQL查询中获取输出,并且没有错误;它也可以快速运行.我检查了该T-SQL查询中的"Date_Completed"和"Review_Date" NULL值,但无论哪种方式,"CompleteDate"始终为NON-Null值.所以我不明白这是怎么回事.

How do I fix this? For some dates, this code above runs perfectly. However for some of the more recent records, it does not. But I am able to get output from the T-SQL query with same date range and there are no errors; it runs quickly also. And I examined this T-SQL query for both "Date_Completed" and "Review_Date" NULL values, but either way, "CompleteDate" was always = NON-Null value. So I do not understand how this is happening.

这是我的VB.NET查询:

Here is my VB.NET query:

            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"

当我将此行添加到上面的导致错误的行上方时,我的报告在这几个月中都超时了.那该怎么办?

When I add this line above the error-causing line above, my report times out for these months. So what to do?

If Not dRow("CompleteDate") Is System.DBNull.Value Then

推荐答案

在要求输入值之前,请使用dRow.IsNull("CompleteDate")检查是否为空.

check for null with dRow.IsNull("CompleteDate") before you ask for the value.

或者,如果这不可能"进行,请将您的查询更改为从不返回可以为null的行.

Or if this is 'supposed to be' impossible, change your query to never return rows where it can be null.

这篇关于从类型&amp;#39; DBNull&amp;#39;的转换键入&amp;#39; Date&amp;#39;无效的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆