1

我需要填写一个时间表以使用它来加入报告服务中的数据。通常,我使用以下代码执行此操作:

TRUNCATE TABLE tqTimeTable

DECLARE @CNT int
DECLARE @DATE datetime
DECLARE @END int

SET @CNT  = 1
SET @DATE = 25567 -- 01.01.1970
SET @END  = 20000 -- + 20k days => years 2024

WHILE(@CNT < @END)
BEGIN
  INSERT INTO tqTimeTable (Tag, Monat, Jahr)
  VALUES (DATEADD(day,@CNT,@DATE), MONTH(DATEADD(day,@CNT,@DATE)), YEAR(DATEADD(day,@CNT,@DATE)))
  SET @CNT = @CNT + 1
END;

但这需要一段时间(在我的测试系统上大约需要 2 分钟),所以我希望有人遇到同样的问题并且比我解决得更好。当我从 .NET 连接触发此语句时,我需要一个更快的解决方案,或者如果没有一个解决方案来提高我的连接超时。

4

1 回答 1

5

只需添加

BEGIN TRAN
WHILE(@CNT < @END)
BEGIN
  INSERT INTO tqTimeTable (Tag, Monat, Jahr)
  VALUES (DATEADD(day,@CNT,@DATE), MONTH(DATEADD(day,@CNT,@DATE)), YEAR(DATEADD(day,@CNT,@DATE)))
  SET @CNT = @CNT + 1
END;
COMMIT

当您进行许多单独的提交(都需要将日志写入磁盘)时,会加快速度。不过,我会在单个语句中进行基于集合的插入。

   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
    )                                       -- 1*10^1 or 10 rows
    , E2(N) AS (SELECT 1 FROM E1 a, E1 b)   -- 1*10^2 or 100 rows
    , E4(N) AS (SELECT 1 FROM E2 a, E2 b)   -- 1*10^4 or 10,000 rows
    , E8(N) AS (SELECT 1 FROM E4 a, E4 b)   -- 1*10^8 or 100,000,000 rows
    , NUMS(N) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT 0)) FROM  E8)
INSERT INTO tqTimeTable
            (Tag,
             Monat,
             Jahr)
SELECT DATEADD(day, N, @DATE),
       MONTH(DATEADD(day, N, @DATE)),
       YEAR(DATEADD(day, N, @DATE))
FROM   NUMS
WHERE  N <= 20000 
于 2013-06-13T09:43:29.030 回答