Wednesday, March 28, 2012

Putting Date into SQL Server

I'm trying to put a date into a SQL Server table. The database field type is "smalldatetime". The variable dDate is type "date" and contains: 2/2/2006 (although I think Cdate actually converts it to: #2/2/2006#). When I run the following code the date in the database is always ends up being: 1/1/1900.

Dim cmd As SqlCommand = New SqlCommand("INSERT INTO MyTable(MyDate) " & _
"VALUES (" & dDate & ")", SqlConn)
daAppts.InsertCommand = cmd
daAppts.InsertCommand.Connection = SqlConn
daAppts.InsertCommand.ExecuteNonQuery()

Any other field types work fine, it's just dates that aren't working ?? Can someone please provide a code snippet showing me what I'm doing wrong??

Dates have to be single quoted:

Dim cmd As SqlCommand = New SqlCommand("INSERT INTO MyTable(MyDate) " & _
"VALUES ('" & dDate & "')", SqlConn)

For clarity, here is the problem part enlarged (with the added single quotes):

('" & dDate & "')


|||That worked. Thank you.|||

Dim cmd As SqlCommand = New SqlCommand("INSERT INTO MyTable(MyDate) " & _
"VALUES (@.dDate)", SqlConn)
cmd.parameters.add("@.dDate",sqldbtype.datetime).value=dDate
daAppts.InsertCommand = cmd
daAppts.InsertCommand.Connection = SqlConn
daAppts.InsertCommand.ExecuteNonQuery()

If you must continue to use string concatenation, atleast pass sql server dDate.ToString("s") as the string format. That will prevent any ambiguity of the format you are giving it. Otherwise you might be suprised when your program dies when you start playing with cultures, and SQL Server misinterprets that date.

No comments:

Post a Comment