简体   繁体   English

确定日期字段是否包含NULL值

[英]Determining if a date field contains a NULL value

I've got this little block of code in a code-behind form: 我在代码隐藏形式中得到了这个小代码块:

using (SqlConnection connection1 = new SqlConnection(str))
{
    using (SqlCommand cmd = new SqlCommand("usp_select_claim_id_MERGE", connection1))
    {
        cmd.CommandType = CommandType.StoredProcedure;

        connection1.Open();
        {
            using (SqlDataReader DT = cmd.ExecuteReader())
            {

            //Format the Orig Open Date to strip off the time and just leave the date
            if ((DT["Orig_Open_Date"]) == null)
              {
                OrigOpenDt = Convert.ToDateTime("1/1/1900");
                OrigOpenDt2 = "";
              }
              else
              {
                OrigOpenDt = Convert.ToDateTime(DT["Orig_Open_Date"]);
                OrigOpenDt2 = OrigOpenDt.ToString("MM/dd/yyyy");
              }

When it hits the IF statement, it's telling me it's false, so the code jumps to the "else" statement. 当它命中IF语句时,它告诉我它是错误的,所以代码跳转到“else”语句。 But when I look at the SQL Server table at the record in question, it looks like this (I'm actually just looking at the first record in the image below): 但是,当我查看相关记录中的SQL Server表时,它看起来像这样(我实际上只是查看下图中的第一条记录):

在此输入图像描述

Looks to me like Orig_Open_Date (the column all the way to the right) has NULLs in it. 在我看来像Orig_Open_Date(一直到右边的列)中有NULL。

If I grab a record where there is actually a date in Orig_Open_Date, it works fine. 如果我抓取一条记录,其中在Orig_Open_Date中实际存在日期,则它可以正常工作。 If there's no date, it still tries to run the "else" statement, so my "if" statement must be wrong. 如果没有日期,它仍会尝试运行“else”语句,因此我的“if”语句必定是错误的。

Admittedly, I'm a C# n00b. 不可否认,我是C#n00b。 What am I doing wrong here? 我在这做错了什么?

尝试DBNull.Value

if(value == DBNull.Value)

您也可以在SQL语句中执行此操作:

Select ISNULL(Orig_Open_Date,'1/1/1900') as Orig_Open_Date

The reason why you recieved a empty value is because of the null value that the reader retrun from the DB. 您收到空值的原因是读者从数据库返回的空值。 I often encounter this problem and now i always check for DBNull.value. 我经常遇到这个问题,现在我总是检查DBNull.value。

Exemple : 例如:

db.GetCommand().CommandText = "SELECT * FROM EMPLOYE";
IDataReader reader = db.GetCommand().ExecuteReader();

if(reader.Read())
{
if(reader["HierdDate"] == DBNull.Value)
// Do that
else
//Do this
}

It's always a good thing to check the DBNull value that a DataReader can return. 检查DataReader可以返回的DBNull值总是一件好事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM