我试图通过SQL以给定的间隔返回开始和结束时间之间的所有有效时间段,但是我有一个心理块很大的时间。下面是一些带有一些变量的示例代码,然后是一个用于存储每个值的表。变量使用INT,因为最终存储值的数据类型是INT,不能更改
DECLARE @StartTime INT = 900
DECLARE @EndTime INT = 2000
DECLARE @CurrentTime INT = 900
DECLARE @Interval INT = 15
DECLARE @Times TABLE
(
[Time] INT
)
WHILE (@CurrentTime <= @EndTime)
BEGIN
INSERT INTO @Times VALUES (@CurrentTime)
SET @CurrentTime = @CurrentTime + @Interval
END
当上面运行时,它会填充,但会给我无效的值。返回值:
900
915
930
945
960
975
etc.
期望的结果是:
900
915
930
945
1000
1015
1030
etc.
有没有办法做到这一点,通过划分当前值并期望一个余数,或者一种简单的方法来达到预期的结果?
由于
答案 0 :(得分:2)
试试这个
DECLARE @StartTime INT = 900
DECLARE @EndTime INT = 2000
DECLARE @CurrentTime INT = 900
DECLARE @Interval INT = 15
DECLARE @Times TABLE
(
[Time] INT
)
WHILE (@CurrentTime <= @EndTime)
BEGIN
INSERT INTO @Times VALUES (@CurrentTime)
SET @CurrentTime = @CurrentTime + @Interval
IF(RIGHT(@CurrentTime,2) = 60)
SET @CurrentTime = @CurrentTime + 40
END
SELECT * FROM @Times
答案 1 :(得分:1)
这有点复杂,但与上述答案有几点不同:它可以跨越午夜,处理非60因子的间隔(以7的间隔尝试上述),并使用递归CTE生成数字而不是WHILE循环。
对INT数据类型感到遗憾,它具有TSQL的TIME数据类型的所有奖励。你可以取消帮助函数。
MAXRECURSION选项有时会出现问题,因为您无法在视图中使用它...调用语句必须指定它。要解决此问题,请将其包装在多语句表值函数中。 see this post
CREATE FUNCTION dbo.ConvertIntToTime (@TimeAsInt INT)
RETURNS TIME
BEGIN
DECLARE @TimeString VARCHAR(4) = RIGHT(REPLICATE('0',4) + CAST(@TimeAsInt AS VARCHAR(4)),4);
RETURN PARSE(LEFT(@TimeString,2) + ':' + RIGHT(@TimeString,2) AS TIME);
END;
GO
CREATE FUNCTION dbo.ConvertTimeToInt (@Time TIME)
RETURNS INT
BEGIN
DECLARE @TimeString VARCHAR(5) = CONVERT(VARCHAR(5), @Time, 108);
RETURN PARSE(LEFT(@TimeString,2) + RIGHT(@TimeString,2) AS INT);
END;
GO
DECLARE @CurrentTime AS INT = 900;
DECLARE @EndTime AS INT = 1700;
DECLARE @Interval AS INT = 10;
DECLARE @CurrentTimeAsTime TIME = dbo.ConvertIntToTime(@CurrentTime);
DECLARE @EndTimeAsTime TIME = dbo.ConvertIntToTime(@EndTime);
WITH CTEGenerateTimes AS
(
SELECT @CurrentTimeAsTime Time
UNION ALL
SELECT DATEADD(MINUTE, @Interval, Time) AS TIME
FROM CTEGenerateTimes
WHERE (@EndTimeAsTime >= @CurrentTimeAsTime AND DATEADD(MINUTE, @Interval, Time) <= @EndTimeAsTime AND DATEADD(MINUTE, @Interval, Time) <> CAST('00:00' AS TIME)) --Range doesn't cross midnight
OR (@EndTimeAsTime < @CurrentTimeAsTime AND DATEADD(MINUTE, @Interval, Time) > @CurrentTimeAsTime AND DATEADD(MINUTE, @Interval, Time) <= CAST('23:59:59' AS TIME)) --Range crosses midnight, portion before midnight
OR (@EndTimeAsTime < @CurrentTimeAsTime AND DATEADD(MINUTE, @Interval, Time) <= @CurrentTimeAsTime AND DATEADD(MINUTE, @Interval, Time) <= @EndTimeAsTime)
)
SELECT dbo.ConvertTimeToInt(t.Time) Time
FROM CTEGenerateTimes t
OPTION (MAXRECURSION 1441)