I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?
I'm trying to achieve the last possible time of a particular day eg for Date of 2008-01-23 00:00:00.000 i would need 2008-01-23 23:59:59.999 perhaps by using the dateadd function on the Date field?
5条答案
按热度按时间ct3nt3jp1#
The answer is
SELECT DATEADD(ms, -3, '2008-01-24')
, the explanation is below.From Marc's blog :
But wait, Marc... you said you like to use
BETWEEN
, but that query doesn't have one... that's becauseBETWEEN
is inclusive , meaning it includes the end-points. If I had an Order that was due at midnight of the first day of the next month it would be included. So how do you get the appropriate value for an end-of-period? It's most certainly NOT by using date-parts to assemble one (but is you must, please remember that it's 23:59:59.997 as a maximum time... don't forget the milliseconds). To do it right, we use the incestuous knowledge that Microsoft SQL ServerDATETIME
columns have at most a 3 millisecond resolution (something that is not going to change). So all we do is subtract 3 milliseconds from any of those end-of-period formulas given above. For example, the last possible instant of yesterday (local time) is:So to do the orders due this month as a
BETWEEN
query, you can use this: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.
wyyhbhjk2#
I thought you had c# at first.. I will leave this here in case anyone else stumbles across this.
You can replace the 'now' variable with whatever day you are trying to figure out
4ktjp1zp3#
Add -1 milliseconds to the start of the next day (DateAdd even supports nanoseconds, if you want to get real fine).
But most likely you just want to use this value in a comparison, and in that case it's even simpler.
Rather than something like this:
or this:
Do it like this:
or this:
xtfmy6hx4#
Why back into it?
aor9mmx15#
I was able to use:
or
to get the end of a day