我正在尝试编写一个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。我想知道为什么会这样。
提前致谢。
答案 0 :(得分:0)
尝试这样的事情......
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)