Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ADD time 23:59:59.999 to end date for between

I have been having an issue with using the following:

Column_Name BETWEEN @StartDate AND @EndDate.  

This is because the @EndDate = 00:00:00.000 for the time, which doesn't pick up all the values for that day.

How would I convert the @EndDate (Always 00:00:00.000) to always be Date + 23:59:59.999?

like image 529
mameesh Avatar asked Oct 07 '11 19:10

mameesh


People also ask

What is the correct way to add a number of hours to a date value in SQL?

If you are using mySql or similar SQL engines then you can use the DATEADD method to add hour, date, month, year to a date. select dateadd(hour, 5, now()); If you are using postgreSQL you can use the interval option to add values to the date.

How do I get the last time of the day in SQL?

The answer is SELECT DATEADD(ms, -3, '2008-01-24') , the explanation is below. Remember, always make sure that you do math against input parameters, NOT columns, or you will kill the SARG-ability of the query, which means indexes that might have been used aren't. This is great!


2 Answers

One option that avoids needing to add EndDate + 23:59:59.999 is to not use the between comparison and instead use column_name >= @StartDate and column_name < @EndDate +1

like image 137
dave Avatar answered Sep 20 '22 22:09

dave


Please note the accuracy and rounding of the DATETIME type in SQL Server 2005:

datetime values are rounded to increments of .000, .003, or .007 seconds

SQL Server 2008 introduced the DATETIME2 type which has an accuracy of 100 nanoseconds. So in SQL Server 2008 you could do:

DECLARE @d DATETIME = '2011-10-07 00:00:00.000' SELECT DATEADD(MS, -1, DATEADD(D, 1, CONVERT(DATETIME2, @d))) 

Alternatively you may want to avoid the BETWEEN operator in this case:

@StartDate <= Column_Name AND Column_Name < DATEADD(D, 1, @EndDate) 
like image 42
Tom Hunter Avatar answered Sep 20 '22 22:09

Tom Hunter