[英]How do I write the SQL to retrieve records for a single date from Access database using C#
I can retrieve all of the records between two dates from an Access database using this statement;我可以使用此语句从 Access 数据库中检索两个日期之间的所有记录;
"SELECT DISTINCT ID_1 as SampleID, ID_2 as TestID FROM Results WHERE TestDate Between #" +
startDate.ToString("MM/dd/yyyy") + "# AND #" + endDate.ToString("MM/dd/yyyy") + "#"
but when I try to get a single date I get no records.但是当我尝试获取单个日期时,我没有任何记录。
"SELECT DISTINCT ID_1 as SampleID, ID_2 as TestID FROM Results WHERE TestDate = #" +
startDate.ToString("MM/dd/yyyy") + "#";
The first attempt did not include the time which is part of the Date field in the data base.第一次尝试不包括作为数据库中日期字段一部分的时间。 So I tried to format the date to include time in HH:mm:ss but that also returned 0 records.所以我尝试格式化日期以在 HH:mm:ss 中包含时间,但也返回了 0 条记录。
What is wrong with the sql statement? sql 语句有什么问题? This is an Access database.这是一个 Access 数据库。
Assuming OleDB:假设 OleDB:
var SQL = @"
SELECT DISTINCT ID_1 as SampleID, ID_2 as TestID
FROM Results
WHERE TestDate >= ? AND TestDate < ?";
var cmd = new OleDbCommand(SQL);
cmd.Parameters.Add("?", OleDbType.Date).Value = startDate.Date;
cmd.Parameters.Add("?", OldDbType.Date).Value = startDate.Date.AddDays(1);
If you're using ODBC it will look similar, with just slightly different naming for the command and enum.如果您使用的是 ODBC,它看起来很相似,只是命令和枚举的命名略有不同。
Some things of note:一些注意事项:
O'Brien
or (ahem) correctly formatting your date literals, but failing to do this is the easiest way I know to find out a year from now that you were hacked six months ago.它不仅速度更快,而且可以帮助您避免基本数据问题,例如姓氏为O'Brien
的人或(咳咳)正确格式化您的日期文字,但不这样做是我知道从现在起一年后找出的最简单方法你六个月前被黑了。datetime
type and let ADO.Net handle this for you via parameterized query.使用 C# datetime
时间类型,让 ADO.Net 通过参数化查询为您处理。>=
on the lower bound and the exclusive <
for the day after the upper bound.对于涵盖全天的日期范围,首选单独条件而不是 BETWEEN,包括>=
下限和排除<
上限之后的一天。 This can sometimes be faster, bust mostly it's just more correct around the boundaries, where BETWEEN can sometimes give the wrong results if you are not careful on how you structure your data and write your boundaries.这有时会更快,但大多数情况下它只是在边界周围更正确,如果您不注意如何构建数据和编写边界,BETWEEN 有时会给出错误的结果。You could strip the time part:你可以去掉时间部分:
"SELECT DISTINCT ID_1 as SampleID, ID_2 as TestID FROM Results " +
"WHERE Fix(TestDate) = #" + startDate.ToString("yyyy'/'MM'/'dd") + "#";
or use an interval:或使用间隔:
"SELECT DISTINCT ID_1 as SampleID, ID_2 as TestID FROM Results " +
"WHERE TestDate >= #" + startDate.ToString("yyyy'/'MM'/'dd") + "# and " +
"TestDate < #" + startDate.AddDays(1).ToString("yyyy'/'MM'/'dd") + "#";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.