Thursday, July 5, 2012

Generate half hour timeslots lookup table in SQL Server

One of the projects required a lookup table with half hour timeslots. For example
Id       Start time       End time
1        12:00 AM         12:30 AM
2        12:30 AM          1:00 AM
3        1:00 AM           1:30 AM

and so on...
Below SQL lets you generate the half hour timeslots for 90 days

declare @dt_date datetime
set @dt_date = '2012-04-30 00:00:00.000' -- Set the start date 

declare @dt_end_date  datetime

set @dt_end_date = (select dateadd(d,90,@dt_date))

declare @counter int =1

while (@dt_date < @dt_end_date )
begin
insert into dbo.your_table_name
select @counter,@dt_date,dateadd(mi,30,@dt_date)
set @dt_date = (select dateadd(mi,30,@dt_date))
set @counter = @counter + 1
end 

No comments: