如果你只是想16年8月30日和16年9月5日之間的一系列天,接下來的日子裏,你可以使用一個派生表的方法如下圖所示。
declare @n int;
declare @StartDate datetime, @EndDate datetime;
set @n = 5;
set @StartDate = '20160830';
set @EndDate = dateadd(day, @n, @StartDate);
select cast(dateadd(day, number, @StartDate) as date) as MyDate,
cast(dateadd(day, number + 1, @StartDate) as date) as MyNextDate
from
(select distinct number from master.dbo.spt_values
where name is null
) n
where dateadd(day, number, @StartDate) < @EndDate;
或者,您可以使用臨時表,表變量來存儲您的日期或cte。
下面給出了一個遞歸cte實例。請注意,您將要設置MAXRECURSION選項,如果你有很長的日期範圍爲默認最大遞歸100
declare @n int;
declare @StartDate datetime, @EndDate datetime;
set @n = 5;
set @StartDate = '20160830';
set @EndDate = dateadd(day, @n, @StartDate);
;with DateSeq as
(
select cast(@StartDate as date) as MyDate
union all
select dateadd(day , 1, MyDate) AS MyDate
from DateSeq where dateadd (day, 1, MyDate) < @EndDate
)
select MyDate, dateadd(day , 1, MyDate) AS NextDate
from DateSeq;
一個臨時表實現的例子如下。
declare @MyDateRange table(MyDate date);
Insert into @MyDateRange values('8/30/2016')
Insert into @MyDateRange values('9/1/2016')
Insert into @MyDateRange values('9/2/2016')
Insert into @MyDateRange values('9/3/2016')
Insert into @MyDateRange values('9/4/2016')
select MyDate, dateadd(day, 1, MyDate) as NextDate from @MyDateRange
有點不清楚。你在尋找一個(用戶驅動的)日期範圍還是多個範圍。另外爲什麼varchar和不約會? –