如何将空日期变量传递到 SQL Server 数据库

问题描述 投票:0回答:4

我正在寻找最佳实践、真正的解决方案,在日期未知时将

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

任何帮助将不胜感激。

sql-server vb.net date null sql-server-2008-r2
4个回答
13
投票

如果日期未知,请发送

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

或者如果您愿意,

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

有必要将变量转换为 Object 类型,以便 If 运算符有一个公共类型可以返回。 Value 参数需要一个对象。


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

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()

-1
投票

试试这个:

Dim purDT As Nullable(Of Date)

If tb2.Text = "" Then
    purDT = DBNull.Value
Else
    purDT = Convert.ToDateTime(tb2.Text)
End If
© www.soinside.com 2019 - 2024. All rights reserved.