我必须根据SQL中存储过程中某个日期的特定时间间隔计算特定开始时间和结束时间之间的所有时间值。
我的存储过程有4个参数。
@date_value nvarchar(1000),//date value'2016-10-09'
@starttime TIME(0) //= '08:00',//suppose starttime is 8am
@endtime TIME(0) //= '13:00'
@interval INT //= '20' //20 minutes
我试图获取starttime和endtime之间的所有时间值。我需要这样的。 8:00,8:20,08:40 ........到12:50(最终价值我不需要)。
我搜索了它,发现我们可以使用
SELECT DATEADD(MINUTE, @MinutesToAdd, @StartTime)
这里我无法包括结束时间。请帮助我
答案 0 :(得分:4)
Declare
@date_value nvarchar(1000)='2016-10-09',
@starttime TIME(0)= '08:00',
@endtime TIME(0) = '13:00',
@interval INT = '20'
;With cte(stime)
as
(
SELECT
cast(cast( @date_value as datetime)
+ CONVERT(CHAR(8), @starttime, 108) as time)
union all
select
cast(dateadd(minute,@interval,stime) as time)
from cte
where cast(dateadd(minute,@interval,stime) as time)<@endtime
)
select * from cte
答案 1 :(得分:2)
以下是没有LOOP
或Recursion
;with cte as
(
SELECT ones.n + 10*tens.n + 100*hundreds.n + 1000*thousands.n as seq
FROM (VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) ones(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) tens(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) hundreds(n),
(VALUES(0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) thousands(n)
),time_gen as
(
SELECT Dateadd(MINUTE, @interval * seq , Cast(Concat(@date_value, ' ', @starttime) AS DATETIME)) as dates
FROM cte
)
select cast(dates as time) times from time_gen
WHERE dates < Cast(Concat(@date_value, ' ', @endtime) AS DATETIME)
order by times
注意:如果您未使用SQL SERVER 2012+
,请使用+
进行连接,而不是Concat
功能
答案 2 :(得分:1)
DECLARE @date_value nvarchar(1000) = '2016-10-09'
DECLARE @starttime TIME(0) = '08:00'
DECLARE @endtime TIME(0) = '13:00'
DECLARE @interval INT = '20'
DECLARE @IterateTime AS TIME(0) = @starttime
DECLARE @Diff AS INT = (SELECT DATEDIFF(MINUTE, @starttime, @endtime)) / @interval
DECLARE @Iterator AS INT = 0
WHILE @Iterator < @Diff
BEGIN
SELECT @IterateTime = DATEADD(MINUTE, @interval, @IterateTime)
SELECT @Iterator = @Iterator + 1
SELECT @IterateTime
END