SQL查询以24小时格式在表中插入所有分钟

时间:2016-05-03 08:22:07

标签: sql-server

我的数据库中有一个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

上述查询有时会导致脚本超时。

3 个答案:

答案 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)

您可以通过以下方式通过Excel生成字段:

insert minutes

传递给A1:INSERT INTO Minutes(Minute) VALUES(

传递给B1:1

传递给C1 )

选择所有3列(A1; B1; C1)并左键单击C1的左下角并向下拖动至1440行。它将生成以下行:

INSERT INTO Minutes(Minute) VALUES(1)
INSERT INTO Minutes(Minute) VALUES(2)
INSERT INTO Minutes(Minute) VALUES(3)
.....

这种方式足够快。

<强>更新

使用单个查询执行此操作,您可以尝试以下操作:

single query