需求
需要将一个时间段的天数全部遍历
了解While函数, dateadd()函数
While{...}
WHILE condition
BEGIN
{...statements...}
END;
当condition满足的时候,一直执行statements
DATEADD(interval, number, date)
-
interval
新增的单位时间,如年(year),月(month),日(day) -
number
新增的数量级 -
date
初始时间
实现
declare @beg varchar(20),@end varchar(20)
select @beg = '2016-11-01',@end = '2016-11-15'
declare @begDate datetime = cast(@beg as datetime),@endDate datetime = cast(@end as datetime)
if DATEDIFF(DAY,@begDate,@endDate) < 0
begin
print '结束时间小于开始时间'
return;
end
DECLARE @newDate datetime
select @newDate = dateadd(day,0,@begDate)
WHILE (DATEDIFF(DAY,@newDate,@endDate) >=0 )
begin
print convert(varchar(20),@newDate,120)
select @newDate = dateadd(day,1,@newDate)
end
F72917DC-6597-42DD-8227-5EC26EF8D7CF.png
网友评论