白猪掌柜的
我认为,为此特定目的,以下查询与使用专用查找表一样有效。DECLARE @start DATE, @end DATE;SELECT @start = '20110714', @end = '20110717';;WITH n AS ( SELECT TOP (DATEDIFF(DAY, @start, @end) + 1) n = ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects)SELECT 'Bob', DATEADD(DAY, n-1, @start)FROM n;结果:Bob 2011-07-14Bob 2011-07-15Bob 2011-07-16Bob 2011-07-17大概您需要将此作为一个集合,而不是单个成员,因此这里是一种适应此技术的方法:DECLARE @t TABLE( Member NVARCHAR(32), RegistrationDate DATE, CheckoutDate DATE);INSERT @t SELECT N'Bob', '20110714', '20110717'UNION ALL SELECT N'Sam', '20110712', '20110715'UNION ALL SELECT N'Jim', '20110716', '20110719';;WITH [range](d,s) AS ( SELECT DATEDIFF(DAY, MIN(RegistrationDate), MAX(CheckoutDate))+1, MIN(RegistrationDate) FROM @t -- WHERE ?),n(d) AS( SELECT DATEADD(DAY, n-1, (SELECT MIN(s) FROM [range])) FROM (SELECT ROW_NUMBER() OVER (ORDER BY [object_id]) FROM sys.all_objects) AS s(n) WHERE n <= (SELECT MAX(d) FROM [range]))SELECT t.Member, n.dFROM n CROSS JOIN @t AS tWHERE n.d BETWEEN t.RegistrationDate AND t.CheckoutDate;----------^^^^^^^ not many cases where I'd advocate between!结果:Member d-------- ----------Bob 2011-07-14Bob 2011-07-15Bob 2011-07-16Bob 2011-07-17Sam 2011-07-12Sam 2011-07-13Sam 2011-07-14Sam 2011-07-15Jim 2011-07-16Jim 2011-07-17Jim 2011-07-18Jim 2011-07-19正如@Dems指出的那样,这可以简化为:;WITH natural AS ( SELECT ROW_NUMBER() OVER (ORDER BY [object_id]) - 1 AS val FROM sys.all_objects) SELECT t.Member, d = DATEADD(DAY, natural.val, t.RegistrationDate) FROM @t AS t INNER JOIN natural ON natural.val <= DATEDIFF(DAY, t.RegistrationDate, t.CheckoutDate);