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)
的值.通過判定相減後值的正負來判定日期的先後