-1

I'm trying to create a method that checks a date to see if it already exists within my database. However I'm getting an exception that the program is having trouble converting from varchar. Anyone able to tell me why it's doing so?

public static int CheckDate(DateTime date)
    {
        using (SqlConnection connection = new SqlConnection(_connectionstring))
        {
            int nooforders = 0;
            connection.Open();
            string SqlQuery = string.Format("SELECT COUNT(OrderID) AS 'OrderCount' FROM OrderTable WHERE DateofCollectionDelivery = '{0}'", date);
            SqlCommand datecheck = new SqlCommand(SqlQuery, connection);
            SqlDataReader sqlDataReader = datecheck.ExecuteReader();
            while (sqlDataReader.Read())
            {
                nooforders = (int)sqlDataReader["OrderCount"];
            }
            connection.Close();
            return nooforders;
        }
    }

This is the method I run and this is the exception:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

The fields in the table have a datatype of datetime, so I'm unsure why it's throwing the exception.

Luke
  • 28
  • 6

2 Answers2

-1

Use the format mm/dd/yyyy or yyyy-mm-dd. use the DateTime.Parse() function to parse your date to this format.

N.Cristian
  • 17
  • 4
  • For the -1, I should give more info's (i think). Use it like this: string SqlQuery = string.Format("SELECT COUNT(OrderID) AS 'OrderCount' FROM OrderTable WHERE DateofCollectionDelivery = '{0}'", DateTime.Parse(data, new CultureInfo("fr-FR", false)).Date); – N.Cristian Mar 16 '18 at 07:45