简体   繁体   English

MS Access SQL-比较一般日期和短日期

[英]MS Access SQL - Compare General Date to Short Date

I need to compare the 2 different date types ( General Date & Short Date ). 我需要比较2种不同的日期类型( 一般日期短日期 )。

I tried to use FORMAT() to able to get the converted date, but you can't use it in WHERE Clause. 我试图使用FORMAT()来获取转换后的日期,但是您不能在WHERE子句中使用它。

"SELECT DT, Item, N, InvoiceNum, FORMAT(DT, 'Short Date') as DT_SD FROM itemHistory WHERE DT_SD='#" & selectedDate & "#')"

You can't use Alias in your where because your alias use in your select. 您不能在您的位置使用Alias,因为您的选择中使用了别名。 Unless you wrap in to subquery 除非您包装到子查询

Reason : 原因:

Where : conditions are evaluated and rows that do not match are removed 其中:评估条件,并删除不匹配的行

So your where statement see as your row not your aliasing. 因此,您的where语句将您的行视为别名,而不是您的行。 Use the full expression instead as stated by @Rene. 如@Rene所述,请使用完整表达式。

"SELECT DT, Item, N, InvoiceNum FROM itemHistory 
WHERE FORMAT(DT, 'Short Date') = #" & selectedDate & "#)"

You should always handle dates as dates, not text. 您应该始终将日期作为日期而不是文本来处理。

For Access SQL, you will have to use a properly formatted string expression for the date values: 对于Access SQL,您将必须使用正确格式的字符串表达式作为日期值:

"SELECT DT, Item, N, InvoiceNum FROM itemHistory WHERE DateDiff('d', DT, #" & Format(selectedDate, "yyyy\/mm\/dd") & "#) = 0"

If DT never contains a time value , this can be reduced to: 如果DT从不包含时间值 ,则可以将其减少为:

"SELECT DT, Item, N, InvoiceNum FROM itemHistory WHERE DT = #" & Format(selectedDate, "yyyy\/mm\/dd") & "#"

This will run faster, if you have an index on field DT. 如果您在字段DT上有索引,它将运行得更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM