1

I have to calculate all the time values which are between a particular start time and end time on the basis of a particular time interval on a date in stored procedure in SQL.

I have 4 parameters for my stored procedure.

@date_value nvarchar(1000),//date value'2016-10-09'
@starttime TIME(0) //= '08:00',//suppose starttime is 8am
@endtime TIME(0) //= '13:00'
@interval INT //= '20' //20 minutes

I am trying to get all the time values between the starttime and endtime. I need it like this. 8:00,8:20,08:40........upto 12:50(end value I dont need).

I have googled it and found that we can use

SELECT DATEADD(MINUTE, @MinutesToAdd, @StartTime)

Here I am not able to include the end time.Please help me

Techy
  • 2,406
  • 7
  • 37
  • 82

3 Answers3

4
Declare
@date_value nvarchar(1000)='2016-10-09',
@starttime TIME(0)= '08:00',
@endtime TIME(0) = '13:00',
@interval INT = '20' 



;With cte(stime)
as
(
SELECT 
cast(cast( @date_value as datetime)
  + CONVERT(CHAR(8), @starttime, 108) as time)
union all
select
 cast(dateadd(minute,@interval,stime) as time)
from cte
where cast(dateadd(minute,@interval,stime) as time)<@endtime 
)
select * from cte
TheGameiswar
  • 26,582
  • 7
  • 53
  • 87
2

Here is one way without LOOP or Recursion

;with cte as
(
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n as seq
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
     (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
     (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
     (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
),time_gen as 
(
SELECT Dateadd(MINUTE, @interval * seq , Cast(Concat(@date_value, ' ', @starttime) AS DATETIME)) as dates
FROM   cte
)
select cast(dates as time) times from time_gen
WHERE  dates < Cast(Concat(@date_value, ' ', @endtime) AS DATETIME)
order by times

Note : If you not using SQL SERVER 2012+, then use + for concatenation instead of Concat function

Pரதீப்
  • 88,697
  • 17
  • 124
  • 160
1
DECLARE @date_value nvarchar(1000) = '2016-10-09'
DECLARE @starttime TIME(0) = '08:00'
DECLARE @endtime TIME(0) = '13:00'
DECLARE @interval INT = '20' 

DECLARE @IterateTime AS TIME(0) = @starttime
DECLARE @Diff AS INT = (SELECT DATEDIFF(MINUTE, @starttime, @endtime)) / @interval
DECLARE @Iterator AS INT = 0


WHILE @Iterator < @Diff
BEGIN
SELECT @IterateTime = DATEADD(MINUTE, @interval, @IterateTime)
SELECT @Iterator = @Iterator + 1
SELECT @IterateTime
END
Esty
  • 1,792
  • 1
  • 16
  • 35