Dealing with DateTime and Null values

10,049

If it's nothing, I think you have to pass the DBNull.Value. Something like this:

If modifieddate Is Nothing then
  command.Parameters.Add(...).Value = DBNull.Value
Else
  command.Parameters.Add(...).Value = modifieddate
End If
Share:
10,049
Internet Engineer
Author by

Internet Engineer

Please visit my personal web site: InternetEngineer.com

Updated on June 14, 2022

Comments

  • Internet Engineer
    Internet Engineer almost 2 years
    1. I have variable called modifieddate of type DateTime, which can be set to null.
    2. I fill in the variable using a datareader and set the value to nothing if the reader is empty
    3. when I use the variable further down, the store procedure complaints that I am not providing the value. "Procedure or function 'tHistory_Insert' expects parameter '@modifieddate', which was not supplied"

    Question: Any ideas on how to pass null values into the store procedure when the date in empty?

    Step 1

    Public modifieddate As Nullable(Of DateTime)
    

    Step 2

    If IsDBNull(dr("modifieddate")) = False Then
    
         modifieddate = DateTime.Parse(dr("modifieddate"))
    Else
    
         modifieddate = Nothing
    End If
    

    Step 3

    command.Parameters.Add("@modifieddate", SqlDbType.DateTime).Value = modifieddate
    command.ExecuteNonQuery()
    
  • Robert Beaubien
    Robert Beaubien over 11 years
    And you don't need to use Nullable(Of DateTime), you can just use DateTime and test for Nothing or use Date.MinValue as your nothing.
  • LarsTech
    LarsTech over 11 years
    @rs. I just tried it. My stored procedure worked without setting the parameter with = null and I passed it the DBNull.Value. Are you referring to the table itself?