如何使用带有日期条件的select语句?

15
在SQL Server中,如何比较日期?
例如:

Select * from Users where RegistrationDate >= '2009-01-20'

(RegistrationDate是datetime类型)
谢谢
6个回答

21

如果您输入

SELECT * FROM Users WHERE RegistrationDate >= '1/20/2009' 
它将自动将字符串“1/20/2009”转换为DateTime格式,日期为“1/20/2009 00:00:00”。因此,使用“> =”应该会得到每个注册日期为1/20/2009或更近的用户。
编辑:我将此放在评论部分,但也应该在此处链接。这是一篇详细介绍如何在查询中处理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

有关DateTime数据类型和SQL Server查询的更多信息,请访问此处: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 - TheTXI

5

如果您不想被日期格式所困扰,可以将该列与一般的日期格式进行比较,例如:

select * From table where cast (RegistrationDate as date) between '20161201' and '20161220'

请确保日期是以DATE格式存在,否则使用 cast (col as DATE) 进行转换。


4
Select * from Users where RegistrationDate >= CONVERT(datetime, '01/20/2009', 103)

这是安全的使用方式,与服务器上的日期设置无关。

完整的样式列表可以在这里找到。


2
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

这个解决方案中的“where”子句不是SARG-able的,所以索引不会被命中。 - GaTechThomas

1

另一个特性是between

Select * from table where date between '2009/01/30' and '2009/03/30'

0

我总是将筛选日期转换为没有时间的日期时间格式(时间= 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/03/30当天开始到包括2009/03/30当天的完整时间。

对于START和END筛选参数,您也可以执行相同的操作。始终将开始日期设置为datetime,并在所需日期的当天使用零时间,并使条件为“> =”。始终将结束日期设置为所需日期后一天的零时间,并使用“<”。这样做,您将始终正确地包括任何日期,而不考虑日期的时间部分。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接