2016-04-21 61 views

回答

1
WITH DATES_CTE AS (
    SELECT TOP 100000 
     ROW_NUMBER() OVER (ORDER BY a.object_id) - 1 AS DayNumber 
    FROM 
     sys.all_columns a 
    CROSS JOIN 
     sys.all_columns b) 
SELECT 
    DATEADD(DAY, DayNumber, 0) AS DateValue 
FROM 
    DATES_CTE 
WHERE 
    DATEADD(DAY, DayNumber, 0) >= '2016-01-01' 
    AND DATEADD(DAY, DayNumber, 0) < '2016-05-01'; 
+0

該解決方案更好,因爲它允許生產超過100行 – user3260061

0

用CTE試試這個。

WITH CTE_DATE 
AS 
( SELECT CONVERT(DATE,'2015-01-01') AS CDATE 
    UNION ALL 
    SELECT DATEADD(DAY,1,CDATE) 
    FROM CTE_DATE 
    WHERE DATEADD(DAY,1,CDATE) <= GETDATE() 
) 
SELECT * FROM CTE_DATE 
option (maxrecursion 0) -- for unlimited recursion 

您可以使用選項option (maxrecursion 0)來避免限制遞歸。

+0

遞歸CTE的遞歸最大值爲100,這隻允許你獲得超過3個月的日期值。 –

+0

@SeanPearce,不,我們可以設置maxrecursion off選項(maxrecursion 0)來實現無限循環。結果已修改。 –

-1
CREATE TABLE #date (datevalues date) 

DECLARE @mindate DATE = '2015-01-01', 
@maxdate DATE = GETDATE() 

WHILE @mindate <= @maxdate 
BEGIN 
    INSERT INTO 
    #date (datevalues) 
    SELECT @mindate 
    SELECT @mindate = dateadd(dd,1,@mindate) 
END 
GO 
SELECT *FROM #date 
GO 
DROP TABLE #date 
GO 
相關問題