Auto-populating a table with DateTime values in SQL server

后端 未结 2 586
攒了一身酷
攒了一身酷 2020-12-22 06:17

I have a table called Appointment in which I want to display appointment slots (60min intervals) from 10am to 3pm for Weekdays

相关标签:
2条回答
  • 2020-12-22 07:09

    You might want to consider using the DATEADD in your insert statements.

    0 讨论(0)
  • 2020-12-22 07:10

    Try this:

    insert Appointment([Date],StartTime,EndTime)
    select cast(DATEADD(day, n, StartTime) as date)
    , cast(StartTime as time)
    , cast(dateadd(hour,1,DATEADD(day, n, StartTime)) as time) 
    from
    (
        select DATEADD(hour, n, '2015-01-01 10:00') StartTime
        from dbo.generate_series(0, DATEDIFF(hour,'2015-01-01 10:00','2015-01-01 15:00'), 1, 0)
    ) StartTimes
    cross join dbo.generate_series(0, DATEDIFF(day,'2015-01-01','2015-08-31'), 1, 0)
    order by AppointmentStart
    

    Uses generate_series from: https://developer42.wordpress.com/2014/09/17/t-sql-generate-series-getting-a-list-of-numbers-in-a-given-range/

    create function dbo.generate_series
    (
          @start bigint
        , @stop bigint
        , @step bigint = 1
        , @maxResults bigint = 0 --0 = unlimited
    )
    returns @results table(n bigint)
    as
    begin
    
        --avoid infinite loop (i.e. where we're stepping away from stop instead of towards it)
        if @step = 0 return
        if @start > @stop and @step > 0 return
        if @start < @stop and @step < 0 return
    
        --ensure we don't overshoot
        set @stop = @stop - @step
    
        --treat negatives as unlimited
        set @maxResults = case when @maxResults < 0 then 0 else @maxResults end
    
        --generate output
        ;with myCTE (n,i) as
        (
            --start at the beginning
            select @start
            , 1
            union all
            --increment in steps
            select n + @step
            , i + 1
            from myCTE 
            --ensure we've not overshot (accounting for direction of step)
            where (@maxResults=0 or i<@maxResults)
            and
            (
                   (@step > 0 and n <= @stop)
                or (@step < 0 and n >= @stop)
            )  
        )
        insert @results
        select n 
        from myCTE
        option (maxrecursion 0) --sadly we can't use a variable for this; however checks above should mean that we have a finite number of recursions / @maxResults gives users the ability to manually limit this 
    
        --all good  
        return
    
    end
    
    0 讨论(0)
提交回复
热议问题