The string was not recognized as a valid C # DateTime server in Sql

I am passing a datetime value from C # to SQL Server SP. If I pass the format dd-MM-yyyy, then it works fine, but does not return any values ​​from the SP, even if there are records of this date. If I run SP with the format MM-dd-yyyy, then it returns the error "Error converting data type nvarchar to datetime". SP

execute usp_detData '22/12/2012 00:00:00', '31/12/2013 23:59:59' --- error

execute usp_detData '12/22/2012 00:00:00', '12/31/2013 23:59:59' --- works great

Could you give me a solution

+5
source share
3 answers

I am passing a datetime value from C # to SQL Server SP.

I believe that you pass it through string concatenation. It is better if you use the SqlParameter type DateTimeand let the server handle it.

using (SqlCommand cmd = new SqlCommand(" usp_detData", conn))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@StartDate", DateTime.Now.AddDays(-10));
    cmd.Parameters.AddWithValue("@EndDate", DateTime.Now);
    SqlDataReader dr = cmd.ExecuteReader();
    .....
}

, IDisposable. . SqlCommand, SqlConnection, SqlDataReader ..

+4

:

DateTime.ParseExact("12/02/21 10:56:09", "dd/MM/YYYY HH:mm:ss", 
    CultureInfo.InvariantCulture
    ).ToString("MMM. dd, yyyy HH:mm:ss")

DateTime

+1

Use the format "yyyy-MM-dd HH: mm: ss" and everything will be fine.

0
source

All Articles