2014-01-07 53 views
1

我想生成一個半小時的時間間隔列表。任何建議都會非常有幫助。我試過這個,並沒有工作。謝謝如何在SQL Server 2012中編寫遞歸CTE小時和分鐘

WITH cte 
AS (select convert(varchar, DATEADD(Day, 0, DATEDIFF(Day, 0, GetDate())), 108) AS Today 

    UNION ALL 

    SELECT dateadd(MINUTE, 30, Today) AS Today 
    FROM cte 
    WHERE dateadd(MINUTE, 30,Today) < (select convert(varchar, DATEADD(Day, 1, DATEDIFF(Day, 0, GetDate())), 108)) 
    ) 
SELECT* 
FROM cte 

要獲取:

0:00 
0:30 
1:00 
1:30 
2:00 
2:30 
3:00 
3:30 
4:00 
4:30 
5:00 
5:30 
6:00 
6:30 
7:00 
7:30 
8:00 
8:30 
9:00 
9:30 
10:00 
10:30 
11:00 
11:30 
12:00 
12:30 
13:00 
13:30 
14:00 
14:30 
15:00 
15:30 
16:00 
16:30 
17:00 
17:30 
18:00 
18:30 
19:00 
19:30 
20:00 
20:30 
21:00 
21:30 
22:00 
22:30 
23:00 
23:30 
0:00 
+0

謝謝bluefeet進行編輯。我仍然在學習正確書寫。 – poshan

回答

1

不能將時間轉換爲VARCHAR,然後用它DATETIME功能,你需要保持它作爲一個DATETIME整個遞歸部分:

;WITH cte AS (SELECT DATEADD(day, 0, DATEDIFF(day, 0, GETDATE())) dt 
       UNION ALL 
       SELECT DATEADD(MINUTE, 30, dt) AS dt 
       FROM cte 
       WHERE dt < DATEADD(day,1,GETDATE()) 
      ) 
SELECT CONVERT(VARCHAR(12),dt, 108) 
FROM cte 
+0

太棒了!謝謝山羊CO – poshan