SQL日期查詢

查詢本日的記錄
select * from tableName where DATEPART(dd, theDate) = DATEPART(dd, GETDATE()) and DATEPART(mm, theDate) = DATEPART(mm, GETDATE()) and DATEPART(yy, theDate) = DATEPART(yy, GETDATE())
查詢本月的記錄
select * from tableName where DATEPART(mm, theDate) = DATEPART(mm, GETDATE()) and DATEPART(yy, theDate) = DATEPART(yy, GETDATE())

查詢本週的記錄
select * from tableName where DATEPART(wk, theDate) = DATEPART(wk, GETDATE()) and DATEPART(yy, theDate) = DATEPART(yy, GETDATE())

查詢本季的記錄
select * from tableName where DATEPART(qq, theDate) = DATEPART(qq, GETDATE()) and DATEPART(yy, theDate) = DATEPART(yy, GETDATE())

查詢 n 天前的記錄
select * from tableName where DATEDIFF(DAY,theDate,GETDATE())=n

查詢 n 年前的記錄
select * from tableName where DATEDIFF(Year,theDate,GETDATE())=n

查詢 n 月前的記錄
select * from tableName where DATEDIFF(Month,theDate,GETDATE())=n

=====================
表名爲:tableName
時間字段名爲:theDate
GETDATE()是獲得系統時間的函數。
=====================
datePart 函數說明
日期部分 縮寫
year yy, yyyy
quarter qq, q
month mm, m
dayofyear dy, y
day dd, d
week wk, ww
weekday dw
Hour hh
minute mi, n
second ss, s
millisecond ms


datediff 函數說明

日期部分 縮寫
year yy, yyyy
quarter qq, q
Month mm, m
dayofyear dy, y
Day dd, d
Week wk, ww
Hour hh
minute mi, n
second ss, s
millisecond ms


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章