我的数据库中有一个Minutes表,我想以24小时格式(从00:00
开始)将所有分钟插入到此表中。我可以使用以下查询执行此操作,但我希望找到一个更快的查询来代替我提出的这个非常基本的查询。
DECLARE @Start as Time(0) = CAST('00:00' as time)
DECLARE @ctr int = 0;
WHILE @ctr<>1440
BEGIN
INSERT INTO Minutes(Minute) VALUES(@Start)
SET @Start = DATEADD(minute, 1, @Start)
SET @ctr = @ctr + 1
END
上述查询有时会导致脚本超时。
答案 0 :(得分:2)
以下是使用Tally table
的基于SET的方法方法,该方法不需要任何循环或递归。
DECLARE @Start as Time(0) = CAST('00:00' as time)
;WITH e1(n) AS
(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
), -- 10
e2(n) AS (SELECT 1 FROM e1 CROSS JOIN e1 AS b), -- 10*10
e3(n) AS (SELECT 1 FROM e1 CROSS JOIN e2), -- 10*100
e4(n) AS (SELECT 1 FROM e1 CROSS JOIN e3),
tally (n) as ( SELECT n = ROW_NUMBER() OVER (ORDER BY n) FROM e4 )
SELECT Dateadd(minute, n - 1, @Start)
FROM tally
WHERE n <= 1440
答案 1 :(得分:2)
使用recursive CTE尝试此操作。
DECLARE @Start as Time(0) = CAST('00:00' as time)
;WITH CTE_TIME AS (
SELECT @Start STIME
UNION ALL
SELECT DATEADD(MINUTE,1,STIME)
FROM CTE_TIME
WHERE DATEDIFF(MINUTE,@Start,STIME) < 1439
)
SELECT * FROM CTE_TIME
OPTION (MAXRECURSION 0)
答案 2 :(得分:1)