I am trying to insert a DateTime
into my SQL Server table column of type DateTime2(7)
using the INSERT INTO syntax.
The error I receive is:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Conversion failed when converting date and/or time from character string.
I initialize the DateTime
variable with:
DateTime TaskCreatedDate = DateTime.Now;
and use it here:
insertTaskCmd.Parameters.AddWithValue("@TaskCreatedDate", TaskCreatedDate);
Any thoughts?
Update:
I have tried:
insertTaskCmd.Parameters.Add("@TaskCreatedDate", SqlDbType.DateTime2).Value = TaskCreatedDate;
with the same error being produced.
Full query:
string insertTask = String.Format("INSERT INTO [Tasks] VALUES (@TaskNumber, '@TaskCreatedDate', '', '', '', @Status, '3', '')");
SqlCommand insertTaskCmd = new SqlCommand(insertTask, conn);
insertTaskCmd.Parameters.AddWithValue("@TaskNumber", newTaskNumbers[i]);
insertTaskCmd.Parameters.Add("@TaskCreatedDate", SqlDbType.DateTime2).Value = TaskCreatedDate.ToString("yyyy-MM-dd HH:mm:ss");
insertTaskCmd.Parameters.AddWithValue("@Status", 0); // 0 is Active
insertTaskCmd.ExecuteNonQuery();