【问题标题】:How to pass a Null date variable to SQL Server database如何将 Null 日期变量传递给 SQL Server 数据库
【发布时间】:2013-02-28 14:03:36
【问题描述】:

我正在寻找最佳实践,真正的解决方案,在日期未知时将Null 发送到 SQL Server 2008 R2 数据库表。

我从表单视图中读取了一些输入,而日期字段可能未知。数据库允许在字段中使用 Null 值,但 VB 在参数化查询更新之前存储 Null 不起作用/让我无法理解。

    Dim tb2 As TextBox = TryCast(FormView1.FindControl("tbPurchDate"), TextBox)
    Dim purDT As Date
    If tb2.Text = "" Then
        IsDBNull(purDT)    ' Tried this along with other possible code
    Else
        purDT = Convert.ToDateTime(tb2.Text)
    End If

任何帮助将不胜感激。

【问题讨论】:

  • 如果你是这个意思,我试过了....将 purDT 调为 Nullable(Of DateTime)
  • 哦,当然,我想我在 OP 中也说过。

标签: sql-server vb.net date null sql-server-2008-r2


【解决方案1】:

试试这个:

Dim purDT As Nullable(Of Date)

If tb2.Text = "" Then
    purDT = DBNull.Value
Else
    purDT = Convert.ToDateTime(tb2.Text)
End If

【讨论】:

    【解决方案2】:

    您可以使用Nullable(Of Date) 让您的purDT 变量也成为Nothing

    Dim purDT As Nullable(Of Date) = Nothing
    
    If tb2.Text <> "" Then
        purDT = Convert.ToDateTime(tb2.Text)
    End If
    

    但是,当您定义将保存该值的 SQL 参数时,奇迹就会发生。参数应为DBNull.Value 或有效(非空)Date

    ' initialize connection, command...
    
    Dim param = New SqlParameter()
    param.ParameterName = "NullableDate"
    param.Value = IIf(purDT Is Nothing, DBNull.Value, purDT)
    
    cmd.Parameters.Add(param)
    cmd.ExecuteNonQuery()
    

    【讨论】:

      【解决方案3】:

      这取决于您用于将数据发送到服务器的数据方法。

      purDate是DateTime类型的变量,不能设置为null。

      我建议你使用 IsDate 而不是测试长度。

          Dim purDT As Date
          If Not IsDate(TextBox1.Text) Then
              purDT = Nothing
          Else
              purDT = Convert.ToDateTime(TextBox1.Text)
          End If
      

      【讨论】:

        【解决方案4】:

        如果日期未知,发送DbNull.Value作为参数值:

        If dateIsUnknown Then
            cmd.Parameters.Add(New SqlParameter _
                               With {.ParameterName = "@purDT", _
                                     .SqlDbType = SqlDbType.Date, _
                                     .Value = DBNull.Value})
        Else
            cmd.Parameters.Add(New SqlParameter _
                               With {.ParameterName = "@purDT", _
                                     .SqlDbType = SqlDbType.Date, _
                                     .Value = theDateVariable})
        End If
        

        【讨论】:

        • Mortan,工作,干净,格式化超出了我的约定,但我可以接受,而且效果很好。非常感谢!!!
        • @marc11h 不客气 :) 我通常也不会那样格式化它,但它确实适合可用的宽度。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-08-08
        • 2012-10-31
        • 1970-01-01
        • 1970-01-01
        • 2017-03-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多