Quantcast
Channel: CodeProject – Tharaka's Blog
Viewing all articles
Browse latest Browse all 36

Comparing time part only without comparing date part in SQL

$
0
0

Recently one of my colleagues asked how to compare only the time part of the DateTime field. I have seen many of us struggling to find an answer for this (Winking smile including me).

If you are one of them, here is a simple solution…

DECLARE @date_to_compare AS DATETIME = '2010-08-08 05:00:00';
DECLARE @date_start AS DATETIME = '2012-08-21 7:00:00';
DECLARE @date_end AS DATETIME = '2012-10-07 13:00:00';

SELECT 'OK'
WHERE  DATEADD(day, -DATEDIFF(day, 0, @date_to_compare), @date_to_compare)
BETWEEN DATEADD(day, -DATEDIFF(day, 0, @date_start), @date_start) AND DATEADD(day, -DATEDIFF(day, 0, @date_end), @date_end)

Above solution work as follows,
It converts the date part of the entered date in to the SQL default date, and then compares it.

SELECT DATEADD(day, -DATEDIFF(day, 0, @date_to_compare), @date_to_compare)
>> 1900-01-01 05:00:00.00

Filed under: CodeProject, SQL Tagged: Database, DateTime

Viewing all articles
Browse latest Browse all 36

Trending Articles