How to generate minute intervals between two dates in T-SQL?

后端 未结 3 919
一个人的身影
一个人的身影 2020-12-20 10:00

I have a table of startTime and endTimes. I need to generate a table of intervals between those two dates in minutes. Here\'s some sample data:

declare @inte         


        
3条回答
  •  粉色の甜心
    2020-12-20 10:51

    You can use recursive query like this :

    declare @intervalMinutes int = 10
    declare @myDates table (
    myId int primary key identity,
    startTime datetime,
    endTime datetime
    )
    
    DECLARE @startTime DATETIME = '2016-07-10 08:00'
    DECLARE @endTime DATETIME = '2016-07-10 09:00'
    
    ;WITH CTE AS
    (
        SELECT  @startTime st
        UNION   ALL
        SELECT  dateadd(MINUTE,@intervalMinutes,st) st
        FROM    cte
        where   dateadd(MINUTE,@intervalMinutes,st) < @endTime
    )
    INSERT INTO @myDates(startTime,endTime)
    SELECT st,dateadd(MINUTE,@intervalMinutes,st) FROM cte
    
    SELECT  * FROm @myDates
    

提交回复
热议问题