在 SQL Server 中比较没有时间的日期的最佳方法
select * from sampleTable
where CONVERT(VARCHAR(20),DateCreated,101)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),101)
我想比较没有时间的日期
上述查询可以吗?或您建议的其他更好的解决方案
- 我正在使用 SQL Server 2005
- 在服务器上以 UTC 格式保存的日期
- 用户针对此数据属于不同的时区
select * from sampleTable
where CONVERT(VARCHAR(20),DateCreated,101)
= CONVERT(VARCHAR(20),CAST('Feb 15 2012 7:00:00:000PM' AS DATETIME),101)
I want to compare date without time
Is above query is ok? or other better solution you suggest
- I am using SQL Server 2005
- Date saved in UTC format on server
- Users against this data belongs different timezone
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
简单地转换为
日期
即可解决该问题。Simple Cast to
Date
will resolve the problem.不要使用转换 - 无缘无故地涉及字符串。一个技巧是,日期时间实际上是一个数字,天数是整数部分(时间是小数部分);因此,日期是值的FLOOR:这只是数学,而不是字符串 - 快得多
在您的情况下,无需转换回日期时间;并且使用范围可以进行最有效的比较(特别是如果有索引):
Don't use convert - that involves strings for no reason. A trick is that a datetime is actually a numeric, and the days is the integer part (time is the decimal fraction); hence the day is the FLOOR of the value: this is then just math, not strings - much faster
In your case, no need to convert back to datetime; and using a range allows the most efficent comparisons (especially if indexed):
缺点是您要铸造过滤柱。
如果过滤列上有索引,那么,由于您正在进行转换,SQL 引擎无法再使用索引来更有效地过滤日期。
The disadvantage is that you are casting the filter column.
If there is an index on the filter column, then, since you are casting, the SQL engine can no longer use indexes to filter the date more efficiently.
描述
不要将 Date 转换为 varchar 并进行比较,因为字符串比较速度不快。
如果您使用
>=
和<
来过滤DateCreated
列,速度会快得多。如果您没有参数(如示例中的字符串),则应使用 ISO 格式
。示例
根据您的示例
更多信息
Description
Don't convert your Date to a varchar and compare because string comparisson is not fast.
It is much faster if you use
>=
and<
to filter yourDateCreated
column.If you have no parameter (like in your sample, a string) you should use the ISO Format
<Year><Month><Day>
.Sample
According to your sample
More Information
请使用 112 CONVERT 格式
或
如果您的 sql server 版本 2008+ 使用
DATE
类型,Use 112 CONVERT's format
or
if your sql server version 2008+ use
DATE
type声明 @DateToday Date= '2019-10-1';
打印@DateToday;
print Abs(datediff(day, @DateToday,CAST('2019 年 10 月 1 日 7:00:00:000PM' AS DATETIME))) < 3
这是3天后的比较。
我在 SQL Server 2014 上测试了这个,它有效。
declare @DateToday Date= '2019-10-1';
print @DateToday;
print Abs(datediff(day, @DateToday,CAST('oct 1 2019 7:00:00:000PM' AS DATETIME))) < 3
this is compare whin 3 days.
i test this on SQL Server 2014, it works.
这还将您的列与特定日期进行比较
不考虑时间
This will also compare your column with the particular date
without taking time into account