7

我正在寻找最佳实践,真正的解决方案,Null在日期未知时将 a 发送到 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

任何帮助将不胜感激。

4

4 回答 4

12

如果日期未知,则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
于 2013-03-12T22:27:33.660 回答
1

您可以使用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()
于 2013-03-12T20:58:38.543 回答
1

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

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

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

    Dim purDT As Date
    If Not IsDate(TextBox1.Text) Then
        purDT = Nothing
    Else
        purDT = Convert.ToDateTime(TextBox1.Text)
    End If
于 2013-03-12T21:03:04.083 回答
-1

试试这个 :

Dim purDT As Nullable(Of Date)

If tb2.Text = "" Then
    purDT = DBNull.Value
Else
    purDT = Convert.ToDateTime(tb2.Text)
End If
于 2013-03-12T20:52:11.483 回答