sql server中对日期字段值的比较

sql server中对日期字段的比较方式有多种,介绍几种常用的方式:

用northwind库中的employees表作为用例表。
1.between...and语句的使用:
说明:between...and用于指定测试范围
看以下实例:
执行sql语句“SELECT hiredate FROM employees”显示结果如下:
hiredate
1992-05-01 00:00:00.000
1992-08-14 00:00:00.000
1992-04-01 00:00:00.000
1993-05-03 00:00:00.000
1993-10-17 00:00:00.000
1993-10-17 00:00:00.000
1994-01-02 00:00:00.000
1994-03-05 00:00:00.000
1994-11-15 00:00:00.000

从以上结果集中搜索出hiredate在"1993-10-17"到"1994-01-02"的记录,则sql语句如下:
SELECT hiredate
FROM employees
WHERE hiredate between cast('1993-10-17' as datetime) and cast('1994-01-02' as datetime)
执行该语句后结果如下:
hiredate
1993-10-17 00:00:00.000
1993-10-17 00:00:00.000
1994-01-02 00:00:00.000
以上sql语句中出现between...and和cast,其中cast是类型转换函数:在该例中将字符串转换成日期型值.
在WHERE中用between...and把"1993-10-17"到"1994-01-02"的记录搜索出来.

2.两个日期值的比较大小可以用< <= > >=运算符,和datediff函数
datediff函数:DATEDIFF ( datepart , startdate , enddate )
datepart的取值可以是year,quarter,Month,dayofyear,Day,Week,Hour,minute,second,millisecond 
startdate 是从 enddate 减去。如果 startdate 比 enddate 晚,返回负值。
看以下实例:
搜索hiredate的值在"1993-05-03"后的记录,该sql语句如下:
SELECT hiredate
FROM employees
WHERE datediff(day,cast('1993-05-03' as datetime),hiredate) >0
执行该语句后结果如下:
hiredate
1993-10-17 00:00:00.000
1993-10-17 00:00:00.000
1994-01-02 00:00:00.000
1994-03-05 00:00:00.000
1994-11-15 00:00:00.000
因此datediff(day,cast('1993-05-03' as datetime),hiredate)是把hiredate的值按"day"减去cast('1993-05-03' as datetime)
的值.通过判定相减后值的正负来判定日期的先后


本文转自:http://www.cnblogs.com/feison/articles/166981.html

袁华慧 编写