[RESOLVED] Puzzled By Date
I put together this code as a test from a project I am working on:
Code:
Dim startDate As String = Date.MinValue.ToShortDateString
Dim endDate As String = "1/1/2025"
Using cn As New SqlClient.SqlConnection(mConString)
Using cmd As SqlClient.SqlCommand = cn.CreateCommand
Using da As New SqlClient.SqlDataAdapter(cmd)
Try
cn.Open()
cmd.Transaction = cn.BeginTransaction
If endDate = "" Then
cmd.CommandText = "DELETE FROM Incubation WHERE [IncubationDate]>= '" & startDate & "'"
Else
cmd.CommandText = "DELETE FROM Incubation WHERE [IncubationDate]>= '" & startDate & "' AND [IncubationDate]<= '" & endDate & "'"
End If
cmd.ExecuteNonQuery()
cmd.Transaction.Rollback()
Catch ex As Exception
If cmd.Transaction IsNot Nothing Then
cmd.Transaction.Rollback()
End If
End Try
End Using
End Using
End Using
Much of this is irrelevant, as it is vestigial remnants from the actual project. The key is that query. I concatenate in a local variable. If that local variable is something like '1/1/2024', then all is well. If the local variable (startDate) is set as shown, then I get an exception stating "The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
So, perhaps SQL Server doesn't like Date.MinValue. That's fine, because I could easily choose some other value that would work just as well. What has me really baffled, though, is that this works just fine in a different method which addresses a different table.
The table that this is failing on, has no data in it. Nor did the table this worked on, when it worked. The field was originally called just plain Date, which I thought was a bad idea, so I changed it to IncubationDate. That shouldn't matter, though, because it appears to all come down to startDate. If that is Date.MinValue, it fails here, while if it is some other date, it works here.
What is going on?
Re: [RESOLVED] Puzzled By Date
Unless you used a parameter that was specifically set to use datetime, I would assume that the database engine is inferring those values to be datetime2, in order for the value to make sense. It probably then converts the existing datetime values in the database to datetime2 for comparison. A query could work with those implicit conversions but trying to save data could not, because the final data type has to be datetime if that's what the target column is set to.