如何将Null日期变量传递给SQL Server数据库 [英] How to pass a Null date variable to SQL Server database

查看:122
本文介绍了如何将Null日期变量传递给SQL Server数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我从formview读了一些输入,而date字段也许是未知的。数据库允许字段中的Null值,但是VB在存储参数化查询更新之前不存在Null。/ / $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $覆盖> Dim tb2 As TextBox = TryCast(FormView1.FindControl(tbPurchDate),TextBox)
Dim purDT As Date
如果tb2.Text =然后
IsDBNull(purDT)'尝试与其他可能的代码
Else
purDT = Convert.ToDateTime(tb2.Text)
如果

任何帮助将不胜感激。

解决方案

如果日期未知,发送 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})
如果


I am looking for the best practice, real solution, to send a Null to a SQL Server 2008 R2 database table, when a date is unknown.

I read some inputs from a formview, and a date field maybe unknown. The database allows Null values in the field but the VB to store the Null prior to a parameterized query update is not working/eludes me.

    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

Any help would be greatly appreciated.

解决方案

If the date is unknown, send DbNull.Value as the parameter's 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

这篇关于如何将Null日期变量传递给SQL Server数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆