【发布时间】:2009-03-30 08:42:57
【问题描述】:
在 sqlserver 中,我如何比较日期? 例如:
从 RegistrationDate >= '1/20/2009' 的用户中选择 *
(RegistrationDate为日期时间类型)
谢谢
【问题讨论】:
标签: sql sql-server
在 sqlserver 中,我如何比较日期? 例如:
从 RegistrationDate >= '1/20/2009' 的用户中选择 *
(RegistrationDate为日期时间类型)
谢谢
【问题讨论】:
标签: sql sql-server
如果你输入
SELECT * FROM Users WHERE RegistrationDate >= '1/20/2009'
它会自动将字符串'1/20/2009' 转换为DateTime 格式的日期1/20/2009 00:00:00。因此,通过使用>=,您应该可以获取所有注册日期为 2009 年 1 月 20 日或更晚的用户。
编辑:我把它放在评论部分,但我可能也应该在这里链接它。这是一篇文章,详细介绍了在您的查询中使用 DateTime 的一些更深入的方法:http://www.databasejournal.com/features/mssql/article.php/2209321/Working-with-SQL-Server-DateTime-Variables-Part-Three---Searching-for-Particular-Date-Values-and-Ranges.htm
【讨论】:
Select * from Users where RegistrationDate >= CONVERT(datetime, '01/20/2009', 103)
使用安全,与服务器上的日期设置无关。
可以在here找到完整的样式列表。
【讨论】:
如果您不想被日期格式所困扰,可以将该列与一般日期格式进行比较,例如
select *
From table
where cast (RegistrationDate as date) between '20161201' and '20161220'
确保日期为 DATE 格式,否则cast (col as DATE)
【讨论】:
select sysdate from dual
30-MAR-17
select count(1) from masterdata where to_date(inactive_from_date,'DD-MON-YY'
between '01-JAN-16' to '31-DEC-16'
12998 rows
【讨论】:
另一个特点是介于:
Select * from table where date between '2009/01/30' and '2009/03/30'
【讨论】:
我总是把过滤器日期变成一个日期时间,没有时间(时间= 00:00:00.000)
DECLARE @FilterDate datetime --final destination, will not have any time on it
DECLARE @GivenDateD datetime --if you're given a datetime
DECLARE @GivenDateS char(23) --if you're given a string, it can be any valid date format, not just the yyyy/mm/dd hh:mm:ss.mmm that I'm using
SET @GivenDateD='2009/03/30 13:42:50.123'
SET @GivenDateS='2009/03/30 13:42:50.123'
--remove the time and assign it to the datetime
@FilterDate=dateadd(dd, datediff(dd, 0, @FilterDateD), 0)
--OR
@FilterDate=dateadd(dd, datediff(dd, 0, @FilterDateS), 0)
您可以使用此 WHERE 子句进行过滤:
WHERE ColumnDateTime>=@FilterDate AND ColumnDateTime<@FilterDate+1
这将给出 2009 年 3 月 30 日当天或之后的所有比赛,直到并包括 2009 年 3 月 30 日的全天
您也可以对 START 和 END 过滤器参数执行相同的操作。始终将开始日期设置为日期时间,并在您想要的那一天使用零时间,并设置条件“>=”。始终将结束日期设为您想要的第二天的零时间并使用“
【讨论】: