mssql 30 minute time intervals beteen 2 datetime

前端 未结 5 1421
余生分开走
余生分开走 2021-01-25 03:10

I have below query and i want to get datetime in 30 min intervals between 2 datetime. Basicly I got it, but is limitited and wouln\'t return al results if the timediff is over 2

5条回答
  •  孤独总比滥情好
    2021-01-25 03:44

    using a recursive Common Table Expression [CTE] is one pretty clean method. For the formatting I am showing FORMAT() from SQL-Server 2012+ you may consider using DATEPART etc to do it though as FORMAT() can have performance impact.

    I do agree with @RossBush's comment if you do things like this a lot generating a calendar (dates) and a time dimensions is very helpful for these purposes.

    DECLARE @DateTime1 DATETIME = '2016/11/24 18:00:00'
    DECLARE @DateTime2 DATETIME = '2016/11/25 06:00:00'
    
    ;WITH cte30MinIncrements AS (
        SELECT @DateTime1 as DT
    
        UNION ALL
    
        SELECT DATEADD(MINUTE,30,DT)
        FROM
           cte30MinIncrements
        WHERE DATEADD(MINUTE,30,DT) <= @DateTime2
    )
    
    SELECT
        *
        ,FORMAT(DT,'dd-HH:mm') as Formated
    FROM
        cte30MinIncrements
    

提交回复
热议问题