【问题标题】:How to insert null in datetime type column in sql server如何在sql server的日期时间类型列中插入null
【发布时间】:2019-12-17 07:21:19
【问题描述】:

我有一个表,其中有一些日期时间类型的列。我使用存储过程将值插入表中。在存储过程中,我有接受 null 以插入表中的变量。我的问题是当我尝试将空值插入表的日期时间列时会引发错误。 我的代码是。

    System.Data.SqlTypes.SqlDateTime getDate;
//set DateTime null
getDate = SqlDateTime.Null;

if (InsertDate.Text == "")
{
cmd1.Parameters["@InsertDate"].Value = getDate;
}
else
{
cmd1.Parameters["@InsertDate"].Value = InsertDate.Text;
}

【问题讨论】:

  • 抛出哪个错误?该列是否允许空值?

标签: c# sql-server


【解决方案1】:
cmd1.Parameters["@InsertDate"].Value = getDate ?? DBNull.Value;

键是 DBNull.Value。我想你有一个可为空的 DateTime 变量,即DateTime? someVariable。你可以测试它是否为空,如果它是使用DBNull.Value(如上所示)。

【讨论】:

    【解决方案2】:
    if (//some condition)   
    {
       cmd.Parameters.AddWithValue("@dateofBirth", txtdob.text);
    }
    else 
    { 
       cmd.Parameters.AddWithValue("@dateofBirth", DBNull.Value); 
    }
    

    【讨论】:

    • 应该添加//some condition 是如果txtdob.Text,或者在OP 的情况下,InsertDate.Text 是否为空...if (!String.IsNullOrEmpty(InsertDate.Text)) 符合要求,在这个例子中。跨度>
    【解决方案3】:

    要将空值传递给 db,您可以使用 DBNull.Value。请试试这个

     if (string.IsNullOrWhiteSpace(InsertDate.Text))
      {
       cmd1.Parameters["@InsertDate"].Value =DBNull.Value;
      }
     else
      {
       cmd1.Parameters["@InsertDate"].Value = InsertDate.Text;
      }
    

    【讨论】:

      【解决方案4】:

      试试这个

      System.Data.SqlTypes.SqlDateTime.Null
      

      【讨论】:

      • 考虑扩展您的答案以解释代码如何解决问题。
      【解决方案5】:

      首先,为了能够将null 插入数据库列,该列必须接受nulls。在设计器中打开表,查看相关列是否可为空。如果不是,并且您尝试插入空值,则会收到错误消息:

      无法将值 NULL 插入列“InsertDate”、表“TableName”;列不允许空值。

      也就是说,由于您使用存储过程插入数据,我建议在过程级别使用默认值作为参数,而不是增加应用程序代码的负担。比,你可以不设置应用程序端的参数,它会正常工作:

       create procedure InsertIntoTable
         -- ....other parameters here...
         @InsertDate datetime = null -- this means that if the value is not supplied, 
                                     -- null is used by default
       as begin
         insert into TableName (InsertDate) values (@InsertDate)
       end
      

      在 C# 方面,只需这样做:

      if (!string.IsNullOrWhitespace(InsertDate.Text)) {
        // check to see if the entered text is actually a date
        DateTime insertDate = ... some parsing/verification code...;
        cmd1.Parameters["@InsertDate"].Value = insertDate;
      }
      

      注意这里没有else分支,所以如果InsertDate为空,则根本不发送参数。

      【讨论】:

        【解决方案6】:

        尝试这样的事情,使用 Add 而不是 AddWithValue..

        DB.Parameters.Add("@date", SqlDbType.DateTime).Value = DBNull.Value;
        

        【讨论】:

          【解决方案7】:

          您应该能够直接提供null 作为参数值:

          if (String.IsNullOrWhitespace(InsertDate.Text)) {
              cmd1.Parameters["@InsertDate"].Value = null;
          } else {
              cmd1.Parameters["@InsertDate"].Value = InsertDate.Text;
          }
          

          也切换到使用String.IsNullOrWhitespace() 来检查空字符串。

          【讨论】:

          • 直接使用 null 可能会导致问题,因为可能无法发送参数(取决于语句和/或 commandType)...DbNull.Value 几乎每次都有效
          • @Linky 啊。我个人从来没有遇到过问题,但知道并记住这一点很有趣。
          • 当使用带有 commandType == StoredProcedure 的命令并且 commandText 只是 StoredProcedure 名称时,参数被添加到执行的文本中(例如使用 Sql Server 分析器检查)。如果添加值为 null 的参数,则该参数将不再是执行的 sql 的一部分,并且如果您的存储过程需要此参数,则执行将失败。 SWeko的回答也提到了这一点。如果您正在构建诸如“插入 X (col) 值 (@col)”之类的语句,据我所知,它并没有什么不同。
          【解决方案8】:

          尝试使用:

          if (string.IsNullOrWhiteSpace(InsertDate.Text))
          {
              cmd1.Parameters["@InsertDate"].Value = getDate;
          }
          else
          {
              cmd1.Parameters["@InsertDate"].Value = InsertDate.Text;
          }
          

          【讨论】:

          • 这基本上是他在使用的,是什么引发了错误。问题是因为它正在发送SqlDateTime.Null,无论是他的还是你的,而他应该发送DBNull.Value。
          【解决方案9】:

          在存储过程中做这样的事情:

          insert into table(date)
          values(case when @InsertDate ='' then 
                         null 
                      else 
                         @insertDate 
                 end)
          

          【讨论】:

            【解决方案10】:

            如果 DBNull.Value 不起作用,请尝试此逻辑 .. 使用 DateTime?空

            确保你的数据库字段应该允许为空

            dtexpiry!=null? dtexpiry :(DateTime?) null

            【讨论】:

              【解决方案11】:

              你可以使用它。我没有捷径!!

              if (InsertDate.Text == "") cmd.Parameters.AddWithValue("@enddate", DBNull.Value); 别的 cmd.Parameters.AddWithValue("@enddate", Convert.ToDateTime(InsertDate.Text));

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2018-03-10
                • 2019-02-15
                • 2021-10-22
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2022-01-06
                相关资源
                最近更新 更多