Databases

MS SQL Server 에서 날짜 및 시각 비교하는 SQL

duraboys 2010. 4. 14. 11:18
다음은, HeartbeatTime 필드에 지금보다 5분 이전의 시간이 있는 리스트를 조회하는 SQL이다.

select dm_id, heartbeattime, DATEDIFF(Minute, heartbeattime, GetDate()) as diff
from ADeviceMonitor
where DATEDIFF(Minute, heartbeattime, GetDate()) > 5
order by DM_Id

DATEDIFF 함수는 시간 비교를 하는 내장함수이다.

DATEDIFF

Returns the number of date and time boundaries crossed between two specified dates.

Syntax

DATEDIFF datepart , startdate , enddate )

Arguments

datepart

Is the parameter that specifies on which part of the date to calculate the difference. The table lists dateparts and abbreviations recognized by Microsoft® SQL Server™.

DatepartAbbreviations
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