到目前为止,是否有办法获得分钟间隔为5,10或15分钟?这是一个例子:
2016-07-25 14:00:00.000 || 2016-07-25 18:00:00.000
我想要一个可以返回一组行的函数,具体取决于我给出的参数区间,以便返回:
间隔参数为5分钟时2016-07-25 14:05:00.000
2016-07-25 14:10:00.000
2016-07-25 14:15:00.000
2016-07-25 14:20:00.000
2016-07-25 14:25:00.000
2016-07-25 ...
2016-07-25 18:00:00.000
间隔参数为10分钟时2016-07-25 14:10:00.000
2016-07-25 14:20:00.000
2016-07-25 14:30:00.000
2016-07-25 14:40:00.000
2016-07-25 14:50:00.000
2016-07-25 ...
2016-07-25 18:00:00.000
谢谢!
答案 0 :(得分:1)
使用递归CTE,可将其插入函数..
declare @start datetime='2016-07-25 14:00:00.000'
declare @end datetime='2016-07-25 18:00:00.000'
;With cte(starttime,endtime)
as
(
select @start,@end
union all
select dateadd(minute,5,starttime),endtime
from cte c
where datediff(minute,c.starttime,c.endtime)>0
)
select * from cte
答案 1 :(得分:0)
基本上,我认为你要找的是这个剧本:
CREATE FUNCTION dbo.udf1 (@interval int, @start datetime, @end datetime)
RETURNS @out TABLE (date1 datetime)
BEGIN
--declare @start datetime='2016-07-25 14:00:00.000', @end datetime='2016-07-25 18:00:00.000', @curr datetime
set @curr = @start
while (dateadd(mi,@interval,@curr)<=@end)
begin
set @curr = dateadd(mi,@interval,@curr)
insert into @out
select @curr
end
return;
END
select *
from dbo.udf1(10,'2016-07-25 14:00:00.000','2016-07-25 18:00:00.000')
答案 2 :(得分:0)
您可以使用Numbers / Tally表,但我使用UDF创建动态日期范围
Select * from [dbo].[udf-Create-Range-Date]('2016-07-25 14:00:00.000','2016-07-25 18:00:00.000','MI',5)
请注意,不仅是开始/结束参数,还有DatePart和Increment
返回
RetVal
2016-07-25 14:00:00.000
2016-07-25 14:05:00.000
2016-07-25 14:10:00.000
...
2016-07-25 17:55:00.000
2016-07-25 18:00:00.000
UDF
CREATE FUNCTION [dbo].[udf-Create-Range-Date] (@DateFrom datetime,@DateTo datetime,@DatePart varchar(10),@Incr int)
Returns
@ReturnVal Table (RetVal datetime)
As
Begin
With DateTable As (
Select DateFrom = @DateFrom
Union All
Select Case @DatePart
When 'YY' then DateAdd(YY, @Incr, df.dateFrom)
When 'QQ' then DateAdd(QQ, @Incr, df.dateFrom)
When 'MM' then DateAdd(MM, @Incr, df.dateFrom)
When 'WK' then DateAdd(WK, @Incr, df.dateFrom)
When 'DD' then DateAdd(DD, @Incr, df.dateFrom)
When 'HH' then DateAdd(HH, @Incr, df.dateFrom)
When 'MI' then DateAdd(MI, @Incr, df.dateFrom)
When 'SS' then DateAdd(SS, @Incr, df.dateFrom)
End
From DateTable DF
Where DF.DateFrom < @DateTo
)
Insert into @ReturnVal(RetVal) Select DateFrom From DateTable option (maxrecursion 32767)
Return
End
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2020-10-01','YY',1)
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2020-10-01','DD',1)
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2016-10-31','MI',15)
-- Syntax Select * from [dbo].[udf-Create-Range-Date]('2016-10-01','2016-10-02','SS',1)
答案 3 :(得分:0)
感谢您的回答,我发现了
exec