0

The below code gives me the correct result but in sql could it be done without a recursive cte? Maybe a cross apply.

declare @t table
(locationID int,
 StartTime datetime,
 EndTime datetime
)

 insert @t
 values (1,'1900-01-01 08:00','1900-01-01 19:30')
 ;
 insert @t
 values (2,'1900-01-01 10:00','1900-01-01 15:00')
 ;
 insert @t
 values (3,'1900-01-01 09:30','1900-01-01 21:00')
 ;
with cte_t
as
(
  select locationID, StartTime, EndTime, StartTime as [Time]
  from @t
 union all
  select locationID, StartTime, EndTime, dateadd(mi,30,[Time]) as [Time]
  from cte_t
  where [Time] < [EndTime]
)

select * from cte_t order by locationID
Roger Clerkwell
  • 406
  • 4
  • 19

1 Answers1

0
with sample_data_table
as
(
    select locationID,cast(StartTime as datetime) as StartTime,cast(EndTime as datetime) EndTime
    from (values (1,'1900-01-01 08:00','1900-01-01 19:30')
                ,(2,'1900-01-01 10:00','1900-01-01 15:00')
                ,(3,'1900-01-01 09:30','1900-01-01 21:00')
    ) t(locationID,StartTime,EndTime)
)

, cte_times AS
(
 SELECT  TOP ((DATEDIFF(HOUR , cast('19000101' as datetime), cast('19000102' as datetime))*2))
 ROW_NUMBER() OVER (ORDER BY number) AS rownum,
 DATEADD(minute, (ROW_NUMBER() OVER (ORDER BY number) -1)*30, cast('19000101' as datetime)) AS dt
 FROM [master].dbo.spt_values
 WHERE [type] = N'P' 
)

 select a.*, b.*
 from sample_data_table as a
 inner join cte_times as b on a.StartTime <= b.dt and a.EndTime >= b.dt
 order by a.locationID,b.dt
Roger Clerkwell
  • 406
  • 4
  • 19
  • Tally Table...like I have my example above? so there are only two possible ways rCTE and Tally ( and I guess loop). – Roger Clerkwell May 11 '19 at 08:36
  • 1
    Just search the internet - [numbers table](https://stackoverflow.com/questions/1393951/what-is-the-best-way-to-create-and-populate-a-numbers-table) – SMor May 11 '19 at 11:49