Tuesday, July 27, 2010

TSQL - BETWEEN - DateTime

I was using BETWEEN statement with the column that has data type of DATETIME. When debugging or validating data, i found out that the count is mismatch due to the DATETIME.
Ex:

Create table #BetweenDateTime (RowNumber INT Identity(1,1), DateTimeTest DateTime)

Insert into #BetweenDateTime values ( '2010-07-21 17:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-21 00:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-20 17:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-23 17:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-25 17:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-26 17:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-23 16:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-28 17:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-29 17:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-29 15:11:50.760')
Insert into #BetweenDateTime values ( '2010-07-30 10:11:50.760')
From the above table:

Select * From #BetweenDateTime Where DateTimeTest Between '2010-07-21' And '2010-07-29'

It retrieve the following data:

RowNumber   DateTimeTest
1                     2010-07-21 17:11:50.760
2                     2010-07-21 00:11:50.760
4                     2010-07-23 17:11:50.760
5                     2010-07-25 17:11:50.760
6                     2010-07-26 17:11:50.760
7                     2010-07-23 16:11:50.760
8                     2010-07-28 17:11:50.760
the above retrieved data was invalid.
Solution:

Select * From #BetweenDateTime

Where Dateadd(Day, Datediff(Day, 0, DateTimeTest), 0) Between '2010-07-21' And '2010-07-29'

This returns the following data:
RowNumber  DateTimeTest
1                  2010-07-21 17:11:50.760
2                  2010-07-21 00:11:50.760
4                  2010-07-23 17:11:50.760
5                  2010-07-25 17:11:50.760
6                  2010-07-26 17:11:50.760
7                  2010-07-23 16:11:50.760
8                  2010-07-28 17:11:50.760
9                  2010-07-29 17:11:50.760
10                2010-07-29 15:11:50.760
i.e.  DATEADD(Day, DATEDIFF(Day, 0, DateTimeTest), 0) condition to round the DATETIME value to DATE.

try this for rounding values:
Select GetDate()
Select Dateadd(D, DateDiff(D, 0, GetDate()), 0)
Select Dateadd (M, DateDiff (M, 0, GetDate()), 0)
Select Dateadd (YYYY, DateDiff (YYYY, 0, GetDate()), 0)
Select Dateadd (Hour, DateDiff (HOUR, 0, GetDate()), 0)
I hope this article helps you!!!..
Thank you. :)

No comments: