为什么这个查询需要这么长时间,以及如何提高其性能?

时间:2017-03-27 01:26:37

标签: sql sql-server stored-procedures query-optimization database-performance

我有一个查询,总结一下,将N个相同的行插入表中,唯一的区别是1列的值来自01, ...,N如果已经存在具有该值的列,则不插入任何插入。我的程序是

BEGIN
    DECLARE @i INT = 0;
    WHILE(@i <= @boardPageCeiling)
    BEGIN
        IF NOT EXISTS(SELECT 1 FROM PageArchives WHERE PageType = 'Board' AND PageNum = @i)
        BEGIN
            INSERT INTO PageArchives
                (PageType, ThreadId, Html, PageNum, RetrievalAttempted, RetrievalSucceeded, RetrievalDate, RetrievalPriority, ProcessAttempted, ProcessingSucceeded, ProcessDate)
            VALUES
                ('Board', NULL, NULL, @i, 0, NULL, NULL, 0, 0, NULL, NULL)
        END
        SET @i = @i + 1;
    END
END

这需要20多秒才能执行boardPageCeiling = 6000。鉴于复杂性,似乎非常长。

3 个答案:

答案 0 :(得分:1)

只需使用一个查询。唯一令人困惑的部分是生成一系列数字:

WITH digits(d) as (
      SELECT *
      FROM (VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9)) v(d)
     ),
     n(n) as (
      SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) - 1 as seqnum
      FROM d CROSS JOIN d CROSS JOIN d CROSS JOIN d
     )
INSERT INTO PageArchives (PageType, PageNum, RetrievalDate, RetrievalPriority, ProcessAttempted)
    SELECT 'Board', PageNum, 0, 0, 0
    FROM n
    WHERE n.n <= @boardPageCeiling AND
          NOT EXISTS (SELECT 1 FROM PageArchives pa WHERE pa.PageNum = n.n);

我从NULL中移除了INSERT值,因为这些值默认设置为NULL

答案 1 :(得分:1)

插入下表:

WITH NumberTable  AS (
  SELECT 1 as Number
  UNION ALL
  SELECT Number+1
  FROM NumberTable  
  WHERE Number < 100 
)
SELECT 'Board', NULL, NULL, Number, 0, NULL, NULL, 0, 0, NULL, NULL FROM NumberTable  
where Number not in (SELECT PageNum FROM PageArchives WHERE PageType = 'Board')
OPTION (MAXRECURSION 0);

只是一个示例查询,将您的“

替换为”

答案 2 :(得分:0)

您可以使用合并声明

来改进该查询