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
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