简体   繁体   中英

Insert DateTime into SQL DateTime

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();

I think your insert query is just wrong - you have the @TaskCreatedDate in single quotes - that shouldn't be .....

Try this:

string insertTask = "INSERT INTO [Tasks] VALUES (@TaskNumber, @TaskCreatedDate, '', '', '', @Status, '3', '')";

SqlCommand insertTaskCmd = new SqlCommand(insertTask, conn);
insertTaskCmd.Parameters.Add("@TaskNumber", SqlDbType.Int).Value =  newTaskNumbers[i];
insertTaskCmd.Parameters.Add("@TaskCreatedDate", SqlDbType.DateTime2).Value = TaskCreatedDate;
insertTaskCmd.Parameters.Add("@Status", SqlDbType.Int).Value = 0; // 0 is Active

insertTaskCmd.ExecuteNonQuery();

Note: I would also recommend to always explicitly specify the columns you want to insert into:

string insertTask = @"INSERT INTO [Tasks](TaskNumber, TaskCreatedDate, .., .., .., Status, .. ..)
                      VALUES (@TaskNumber, @TaskCreatedDate, '', '', '', @Status, '3', '')");

Fixed.

Note around the @TaskCreatedDate there are single quotation marks ('). Remove these and it's solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM