【问题标题】:SQL statement where clause by two datesSQL 语句 where 子句按两个日期
【发布时间】:2013-12-25 13:40:12
【问题描述】:

我正在尝试编写一个 Sql 语句,它根据用户输入的两个日期变量过滤记录。这是我的 Sql 语句:

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

但是,它告诉我从字符串转换日期和/或时间时转换失败,尽管我的 packingDate 和 deliveryDate 的数据类型是 DateTime。我想知道为什么会这样。

提前致谢。

【问题讨论】:

    标签: sql date where


    【解决方案1】:

    试试这样的...

    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)
    

    【讨论】:

      猜你喜欢
      • 2019-07-15
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      相关资源
      最近更新 更多