Mustafa Alsamarrai Mustafa Alsamarrai - 3 years ago 171
C# Question

Send date from C# to SQL Server

I have issue with converting

in C# to
in SQL Server.

I constantly get this error message:

input string was not in correct format.

I tried this query

insert into TasksCopy (Start_Date)
values (CONVERT(date, '10/01/2017'));

It worked in SQL Server Management Studio, but didn't work using C# program in Visual Studio.

However the query below worked in both Visual Studio and Management Studio:

insert into TasksCopy (Time)
values (CONVERT(time, '17:00:00'));

I tried this way using my C# app to send
variable called

insert into TasksCopy (Start_Date)
values (CONVERT(date,"mm/dd/yyyy")));

however that still did not work.

The code below did not work either:

string query = $"insert into TasksCopy (Start_Date) values (CONVERT(date, @date));";

SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@date", dateTime.Date);

That also did not work.

What is the correct way to send data to SQL Server as
data type?

Thanks in advance

Answer Source

date managing is always a pain no matter what language, but somehting that seems to always work in SQL engines is to send the date string as


So you can try something like this:

insert into TasksCopy (Start_Date) values (CONVERT(date,"yyyy-mm-dd")));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download