Question

I am trying to write a Sql statement which filter the records based on two date variables entered by users. Here is my Sql statement:

         public List<DistributionPacking> filterByDeliveryDate()
    {
        List<DistributionPacking> dateList = new List<DistributionPacking>();

        using (var connection = new SqlConnection(FoodBankDB.connectionString)) // get your connection string from the other class here
        {
            SqlCommand command = new SqlCommand("SELECT d.id, d.packingDate, d.deliveryDate, b.name FROM dbo.Distributions d " +
                "INNER JOIN dbo.Beneficiaries b ON d.beneficiary = b.id WHERE d.deliveryDate BETWEEN @fromDate AND @toDate", connection);
            command.Parameters.AddWithValue("@fromDate", startDate);
            command.Parameters.AddWithValue("@toDate", endDate);
            connection.Open();
            using (var dr = command.ExecuteReader())
            {
                while (dr.Read())
                {
                    string id = dr["id"].ToString();
                    DateTime packingDate = DateTime.Parse(dr["packingDate"].ToString());
                    DateTime deliveryDate = DateTime.Parse(dr["deliveryDate"].ToString());
                    string name = dr["name"].ToString();

                    dateList.Add(new DistributionPacking(id, packingDate, deliveryDate, name));
                }
            }
        }

However, it told me that Conversion failed when converting date and/or time from character string although my data type for packingDate and deliveryDate is DateTime. I wonder why is it so.

Thanks in advance.

Was it helpful?

Solution

Try something like this ...

SELECT d.id, d.packingDate, d.deliveryDate, b.name 
FROM dbo.Distributions d  INNER JOIN dbo.Beneficiaries b 
ON d.beneficiary = b.id 
WHERE d.deliveryDate 
     BETWEEN CAST(@fromDate AS DATETIME) AND CAST(@toDate AS DATETIME)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top