我不会循环创建日期列表,使用数字表(不仅仅是值 0 到 9 的表),它们对很多事情都很有用:http: //web.archive.org/web/20150411042510/http ://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-numbers-table.html使用真正的 Numbers 表,您不必多次交叉连接并制作查询过于复杂。
要使此方法起作用,您需要执行此一个时间表设置:
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
INTO Numbers
FROM sys.columns s1
CROSS JOIN sys.columns s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)
设置 Numbers 表后,使用以下查询:
SELECT
@Start+Number-1
FROM Numbers
WHERE Number<=DATEDIFF(day,@Start,@End)+1
捕捉他们做:
DECLARE @Start datetime
,@End datetime
DECLARE @AllDates table
(Date datetime)
SELECT @Start = '06/23/2008', @End = '06/30/2008'
INSERT INTO @AllDates
(Date)
SELECT
@Start+Number-1
FROM Numbers
WHERE Number<=DATEDIFF(day,@Start,@End)+1
SELECT * FROM @AllDates
输出:
Date
-----------------------
2008-06-23 00:00:00.000
2008-06-24 00:00:00.000
2008-06-25 00:00:00.000
2008-06-26 00:00:00.000
2008-06-27 00:00:00.000
2008-06-28 00:00:00.000
2008-06-29 00:00:00.000
2008-06-30 00:00:00.000
(8 row(s) affected)