使用while循环不能正确循环日期

时间:2015-06-21 09:02:42

标签: sql sql-server date

我有这样的查询:

declare @currentDate datetime,@enddate datetime;

set @currentDate = '06/1/2015';
select @enddate='06/05/2015'

while @currentDate < @enddate



begin



select @currentDate = dateadd(DAY,1,@currentDate);
select @currentDate as currentdate
end

但是在结果集中这没有显示我当前的日期。在s显示2015-06-02关于病房的日期..我想要包括我当前的日期

2 个答案:

答案 0 :(得分:1)

这就是我的意思:

declare @currentDate datetime,@enddate datetime

set @currentDate = '20150601'
set @enddate='20150605'

while (@currentDate <= @enddate) begin
  select @currentDate as currentdate
  select @currentDate = dateadd(DAY,1,@currentDate)
end

答案 1 :(得分:0)

你在while循环中做的第一件事是增量currentDate。这将立即从2015年6月1日到2015年6月6日将其移至:

declare @currentDate datetime,@enddate datetime;
set @currentDate = '06/1/2015';
select @enddate='06/05/2015'
while @currentDate < @enddate --- May need to be <= if inclusive range.
begin    
    --- Do stuff with currentDate here THEN increment at the very end.
    set @currentDate = dateadd(DAY,1,@currentDate);
end