这是一个使用内联表值函数的解决方案,您可以重复使用该函数来获取任何间隔的日期所需的任何范围。您可以通过将日期时间转换为字符串并在其上使用字符串函数来获得所需的确切输出。
--A function that returns all intervals between start and end
CREATE FUNCTION GetTimeIntervals
(
@intervalMinutes int
,@startDateTime datetime
,@endDateTime datetime
)
RETURNS TABLE
AS
RETURN
(
WITH cSequence AS
(
SELECT
@startDateTime AS C_StartDateTime
,DATEADD(minute, @intervalMinutes, @startDateTime) AS C_EndDateTime
UNION ALL
SELECT
C_EndDateTime AS C_StartDateTime
,DATEADD(minute, @intervalMinutes, C_EndDateTime) AS C_EndDateTime
FROM cSequence
WHERE DATEADD(minute, @intervalMinutes, C_EndDateTime) <= @endDateTime
)
select C_StartDateTime, C_EndDateTime FROM cSequence
);
GO
--Example implementation
DECLARE @times TABLE (Id INT IDENTITY(1,1),time1 DATETIME,time2 DATETIME);
INSERT INTO @times VALUES ('2013-05-07 08:00','2013-05-07 10:00'),('2013-05-08','2013-05-09')
DECLARE @Interval INT = 30;
SELECT
Id
,fn.C_StartDateTime
,fn.C_EndDateTime
,REPLACE(RIGHT(CONVERT(VARCHAR(16),fn.C_StartDateTime,121),5)+'-'+RIGHT(CONVERT(VARCHAR(16),fn.C_EndDateTime,121),5),':','') AS Interval
FROM @times AS t
CROSS APPLY GetTimeIntervals(@Interval,time1,time2) AS fn
OPTION(MAXRECURSION 0)