码迷,mamicode.com
首页 > 其他好文 > 详细

生成两个时间之间的所有日期

时间:2017-01-03 15:21:34      阅读:179      评论:0      收藏:0      [点我收藏+]

标签:returns   return   end   max   span   creat   function   --   时间   

--改写liangCK的部分代码为函数
--创建函数
create function generateTime
(
    @begin_date datetime,
    @end_date datetime
)
returns @t table(date datetime)
as
begin
    with maco as
    (
       select @begin_date AS date
       union all
       select date+1 from maco
       where date+1 <=@end_date
    )
    insert into @t
    select * from maco option(maxrecursion 0);
    return
end
 
Go
--测试示例
select * from dbo.generateTime(2009-01-01,2009-01-10)
 
--运行结果
/*
date
-----------------------
2009-01-01 00:00:00.000
2009-01-02 00:00:00.000
2009-01-03 00:00:00.000
2009-01-04 00:00:00.000
2009-01-05 00:00:00.000
2009-01-06 00:00:00.000
2009-01-07 00:00:00.000
2009-01-08 00:00:00.000
2009-01-09 00:00:00.000
2009-01-10 00:00:00.000
*/
 
 
 
go
--第二版
--创建函数
create function generateTimeV2
(
    @begin_date datetime,
    @end_date datetime
)
returns @t table(date datetime)
as
begin
    insert into @t
    select dateadd(dd,number,@begin_date) AS date
    from master..spt_values
    where type=p and dateadd(dd,number,@begin_date)<=@end_date
    return
end
 
--测试示例
select * from dbo.generateTimeV2(2009-01-01,2009-01-10)
--运行结果
/*
date
-----------------------
2009-01-01 00:00:00.000
2009-01-02 00:00:00.000
2009-01-03 00:00:00.000
2009-01-04 00:00:00.000
2009-01-05 00:00:00.000
2009-01-06 00:00:00.000
2009-01-07 00:00:00.000
2009-01-08 00:00:00.000
2009-01-09 00:00:00.000
2009-01-10 00:00:00.000
 
(10 row(s) affected)
*/

 

生成两个时间之间的所有日期

标签:returns   return   end   max   span   creat   function   --   时间   

原文地址:http://www.cnblogs.com/accumulater/p/6244719.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!