I have a web app with a form that I am trying to pass to an ASP.NET server (using VB.NET) and then on to a MS SQL Server table. The form uses a jQuery datepicker in several textboxes and formats them as MM/dd/yyyy. The form fields are then passed through a PageMethod to the web server which takes the various field values and combines them into a SQL UPDATE command.
I am constantly getting the following error whenever I try to execute the SQL command:
Conversion failed when converting date and/or time from character string.
Here is the code on the server:
Using myConn As New System.Data.SqlClient.SqlConnection(CString.ConnectionString)
myConn.Open()
Dim cmd As New System.Data.SqlClient.SqlCommand("UPDATE table " & _
"SET type = '" & type & "', " & _
"target = '" & "@target" & "', " & _
"patient = '" & patient & "', " & _
"dob = '" & "@dob" & "' " & _
"WHERE serial = '" & serial & "'", myConn)
cmd.Parameters.Add(SqlParameter("@target", Data.SqlDbType.Date))
cmd.Parameters.Add(SqlParameter("@dob", Data.SqlDbType.Date))
If target = "" Then
cmd.Parameters("@target").Value = Data.SqlTypes.SqlDateTime.Null
Else
cmd.Parameters("@target").Value = target
End If
If dob = "" Then
cmd.Parameters("@dob").Value = Data.SqlTypes.SqlDateTime.Null
Else
cmd.Parameters("@dob").Value = dob
End If
cmd.ExecuteNonQuery()
End Using
Note: I've tried about twenty different ways of parsing the dates, converting them to dates, changing around the formats and none of it has worked.
Note 2: The conditional statements at the end are simply to prevent empty date fields from being stored in the SQL DB as "1/1/1900", but rather as an actual SQL NULL value. From debugging though, it seems that this is not the issue - it is when there is an actual value that the error is fired.
If anyone can see what I'm doing wrong and how I might fix it, it would be greatly appreciated. Thanks in advance for your help!