Search code examples
sql-servervb.netdatenullsql-server-2008-r2

How to pass a Null date variable to SQL Server database


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.


Solution

  • 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
    

    Or if you prefer,

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

    It is necessary to cast the variable to be of type Object so that the If operator has a common type to return. The Value parameter expects an Object.