数据库日期/时间比较不会产生预期结果
本文关键字:结果 日期 时间 比较 数据库 | 更新日期: 2023-09-27 18:36:08
我在使用 C# 和 MS Access 时遇到问题,我希望以下调用返回一条记录:
c = Shift.Get(ProfileID, Start, null, null, null, null, null, null);
其中"开始"是"1/7/2015 3:30:00 PM",配置文件 ID 是"******16732",方法是:
public static ObservableCollection<Shift> Get(string profileID, DateTime? start,
DateTime? stop, string fullName, bool? closed, bool? archived = null,
Database db = null, string sort="ASC")
{
OleDbCommand cmd = new OleDbCommand(
"SELECT profiles.profile_id, profiles.full_name, shifts.start, " +
"shifts.stop, shifts.start_log, shifts.stop_log, shifts.notes, " +
"shifts.closed, shifts.archived FROM shifts, profiles WHERE " +
(profileID != null ? "(shifts.profile_id=@profile_id) AND " : "") +
(start.HasValue ? "(shifts.start>=@start) AND " : "") +
(stop.HasValue ? "(shifts.stop<=@stop) AND " : "") +
(fullName != null ? "profiles.full_name=@full_name AND " : "") +
(closed.HasValue ? "shifts.closed=@closed AND " : "") +
(archived.HasValue ? "shifts.archived=@archived AND " : "") +
"(shifts.profile_id=profiles.profile_id) " +
"ORDER BY shifts.start " + sort
);
if (profileID != null)
cmd.Parameters.AddWithValue("@profile_id", profileID);
if (start.HasValue)
cmd.Parameters.AddWithValue("@start", start.Value.ToString());
if (stop.HasValue)
cmd.Parameters.AddWithValue("@stop", stop.Value.ToString());
if (fullName != null)
cmd.Parameters.AddWithValue("@full_name", fullName);
if (closed.HasValue)
cmd.Parameters.AddWithValue("@closed", closed.Value);
if (archived.HasValue)
cmd.Parameters.AddWithValue("@archived", archived.Value);
....
}
给定以下班次表:
profile_id start stop start_log stop_log notes closed archived
******45544 1/7/2015 3:30:00 PM 1/2/2015 11:30:00 PM 1/7/2015 3:06:02 PM 1/2/2015 11:32:40 PM "" Yes No
******12956 1/7/2015 3:30:00 PM 1/2/2015 9:00:00 PM 1/7/2015 3:08:10 PM 1/2/2015 9:15:29 PM "" Yes No
******17392 1/7/2015 2:00:00 PM 1/2/2015 11:30:00 PM 1/7/2015 1:46:07 PM 1/2/2015 11:33:09 PM "" Yes No
******16732 1/7/2015 3:30:00 PM 1/2/2015 6:30:00 PM 1/7/2015 3:08:38 PM 1/2/2015 6:35:03 PM "" Yes No
******15503 1/7/2015 2:00:00 PM 1/2/2015 10:00:00 PM 1/7/2015 1:46:43 PM 1/2/2015 10:01:24 PM "" Yes No
******14536 1/7/2015 3:30:00 PM 1/2/2015 11:30:00 PM 1/7/2015 3:04:12 PM 1/2/2015 11:35:19 PM "" Yes No
但是,我得到的返回没有记录,也没有错误。这很令人惊讶,因为我确实在 SQL 语句的 WHERE 子句中有一个shifts.start >= @start
,并且数据存在。
注意,ProfileID 是模糊的,因为它是敏感的,并且开始日期在停止日期之后开始,这显然是错误的,但那是测试数据,应该与结果无关。如果未提供 db,则存在默认数据库连接。
我不得不做一些编辑,希望我没有在任何地方打错字。
有什么线索吗?
您需要
将 DateTime 作为 DateTime 对象而不是字符串传递(删除 .ToString().这样,该命令将正确分析 DateTime 对象,以便 Access 将其识别为 DateTime。