I’m having a little trouble getting a count of dates in SQL SERVER. I require the number of calender days between 2 dates start and ends dates included. The problem with the example below is that it always returns 10 when I believe it should be 11.
DECLARE @FROM DATETIME, @TO DATETIME
SET @FROM = '18/12/2011 00:00:00'
SET @TO = '28/12/2011 00:00:00'
SELECT
DATEDIFF(MINUTE,@FROM,@TO), -- Returns 14459
DATEDIFF(HOUR,@FROM,@TO), -- Returns 241
DATEDIFF(DAY,@FROM,@TO), -- Returns 10
CEILING(CAST((DATEDIFF(HOUR,@FROM,@TO) / 24) as DECIMAL(9,5))) --Returns 10
CEILING(CAST(CEILING(CEILING(CAST(DATEDIFF(SECOND,@FROM,@TO) as DECIMAL(18,5))) / 60) / 60 as DECIMAL(9,5)) / 24) --Returns 10
The bottom line works if there is at least 1 second between the times but I must account for all scenarios.
My only other thought was to simply add one to the date diff to account for the part days? Is that reliable?
DATEDIFF(DAY,@FROM,@TO) + 1
I came across when answering this question How to find the total between the dates for each values
This is taken from MSDN here.
28-18 = 10. I think you will always have to add 1 in the scenario you have because of the definition for DATEDIFF.