设为首页 加入收藏

TOP

SQLServer生成时间范围
2015-07-24 11:04:40 来源: 作者: 【 】 浏览:1
Tags:SQLServer 生成 时间 范围
前面写过类似的文章,这是开发时用的
if OBJECT_ID(N'tf_Data_TimeRange',N'FN') is not null
	drop function tf_Data_TimeRange
go

create function tf_Data_TimeRange(
	@startDate varchar(20), --开始日期
	@endDate varchar(20),   --结束日期
	@dataType int           --数据类型 1:小时 2:日
) returns @temp table(orderby int,MonitorTime varchar(20))
as
/********************************
--function:递归生成时间段
--author:zhujt
--create date:2015-5-28 17:07:11
*********************************/
begin
	if @dataType=1 
		begin
			with temp(orderby,vdate) as
			(select 1 orderby,convert(varchar(20),@startDate,120)
			  union all
			 select orderby+1, convert(varchar(20),dateadd(HOUR,1,vdate),120) 
			   from temp 
			  where vdate < @endDate
			 ) 
			insert into @temp(orderby,MonitorTime)
			select orderby,vdate from temp
			OPTION (MAXRECURSION 0) --排除限值
		end
	else if @dataType=2
		begin 
			set @endDate=convert(varchar(10),@endDate,120);
			
			with temp(orderby,vdate) as
			(select 1 orderby,convert(varchar(10),@startDate,120)
			  union all
			 select orderby+1, convert(varchar(10),dateadd(DD,1,vdate),120) 
			   from temp 
			  where vdate < @endDate
			 ) 
			insert into @temp(orderby,MonitorTime)
			select orderby,vdate from temp
			OPTION (MAXRECURSION 0) --排除限值
		end 
	return;
end

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇sqlite学习笔记8:C语言中使用sql.. 下一篇详解char和varchar的区别

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Redis 分布式锁全解 (2025-12-25 17:19:51)
·SpringBoot 整合 Red (2025-12-25 17:19:48)
·MongoDB 索引 - 菜鸟 (2025-12-25 17:19:45)
·What Is Linux (2025-12-25 16:57:17)
·Linux小白必备:超全 (2025-12-25 16:57:14)