Isola Olufemi Isola Olufemi -4 years ago 58
SQL Question

Getting hours interval between date range

Please can someone help me out here, i am trying to get a table of hours interval between a date range.

For example:

if starttime == 2012-02-06 23:59:00'
then endtime = '2012-02-29 10:26:17'


I should have a table(variable table) with content like this:

Start End Seconds
2012-02-06 23:59:00.000 2012-02-06 23:59:00.000 0
2012-02-29 09:00:00.000 2012-02-29 09:59:00.000 3540
2012-02-29 10:00:00.000 2012-02-29 10:26:17.000 1577

Answer Source

Thanks all for the suggestions and comments.I finally got a was to solve may problem.

Below is the script to the solution i came up with:

DECLARE @start_date datetime = CONVERT(DATETIME,'2012-02-06 23:59:01.000',20);
DECLARE @end_date datetime = CONVERT(DATETIME,'2012-12-08 23:59:17.000',20);
DECLARE @org datetime  ;
DECLARE @end datetime  ;
DECLARE @datetable TABLE (h_start datetime, h_end datetime,h_sesc int);

WHILE (dateadd(second, -1, dateadd(hour, datediff(hour, 0, @start_date)+1, 0))) < @end_date
BEGIN
SET @org = null;
SET @org = @start_date;
SET @end = (dateadd(second, -1, dateadd(hour, datediff(hour, 0, @org)+1, 0)));
INSERT INTO @datetable (h_start, h_end,h_sesc)
VALUES(dateadd(second, 0,@org), @end,DATEDIFF(second, @org,@end));

SET @start_date = dateadd(second, 1,@end);

END;


INSERT INTO @datetable (h_start, h_end,h_sesc)
VALUES(dateadd(second, 0,@start_date), @end_date,DATEDIFF(second, dateadd(second, 0,@start_date),@end_date));

SELECT * FROM @datetable;

The above will give the folowing results:

h_start                 h_end                   h_sesc
2012-02-06 23:59:01.000 2012-02-06 23:59:59.000 58
2012-02-07 00:00:00.000 2012-02-07 00:59:59.000 3599
2012-02-07 01:00:00.000 2012-02-07 01:59:59.000 3599
2012-02-07 02:00:00.000 2012-02-07 02:59:59.000 3599
2012-02-07 03:00:00.000 2012-02-07 03:59:59.000 3599
2012-02-07 04:00:00.000 2012-02-07 04:59:59.000 3599
2012-02-07 05:00:00.000 2012-02-07 05:59:59.000 3599

.. ..

2012-12-08 18:00:00.000 2012-12-08 18:59:59.000 3599
2012-12-08 19:00:00.000 2012-12-08 19:59:59.000 3599
2012-12-08 20:00:00.000 2012-12-08 20:59:59.000 3599
2012-12-08 21:00:00.000 2012-12-08 21:59:59.000 3599
2012-12-08 22:00:00.000 2012-12-08 22:59:59.000 3599
2012-12-08 23:00:00.000 2012-12-08 23:59:17.000 3557

Hope someone will find it useful.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download