执行WHILE循环会花费更长的时间并且卡在Managment工作室

时间:2019-03-11 19:19:10

标签: sql-server tsql

我想在WHILE循环中执行3个存储过程。因此,首先我需要以下数据:

DECLARE @FBOMDesigns AS TABLE
(
      DesignKey INT,
      ParentDesignKey INT,
      ProjectKey INT,
      CurrentRow INT
)

INSERT INTO @FBOMDesigns
    SELECT 
        D.DesignKey, [D].ParentDesignKey,
        [PD].[ProjectKey],
        ROW_NUMBER() OVER(ORDER BY D.[DesignKey]) AS [CurrentRow]
    FROM 
        ##Design AS D  
    INNER JOIN 
        ##ProjectDesign AS PD ON D.DesignKey = PD.DesignKey
    WHERE  
        DesignTypeGuid = '13B58AC4-F8BD-431F-8977-BE9C1FF25C7C'

DECLARE @NewCDDesigns AS TABLE 
(
     DesignKey INT,
     CurrentRow INT
)

INSERT INTO @NewCDDesigns
    SELECT 
        D.DesignKey,
        ROW_NUMBER() OVER (ORDER BY D.DesignKey) AS CurrentRow
    FROM 
        ##Design AS D
    INNER JOIN 
        ##ProjectDesign AS PD ON D.DesignKey = PD.DesignKey
    INNER JOIN 
        @FBOMDesigns as FD ON PD.ProjectKey = FD.ProjectKey
    WHERE 
        PD.ProjectKey IN (SELECT ProjectKey FROM @FBOMDesigns) 
        AND D.DesignTypeGuid = '54FBBC23-CB9A-4311-9D7F-0DD7A774F33D' 
        AND D.Folio = 0

如您所见,我创建了两个带有信息的表

一旦设置好变量,就设置好

DECLARE @counter   INT = 1,
        @max       INT = 0,
        @DesignKey INT

SET @max = (SELECT COUNT(DesignKey) FROM @NewCDDesigns)

注意:@max的值为628

因此循环需要通过628次:

WHILE @counter <= @max
BEGIN
    DECLARE @CurrentDesignKey INT = (SELECT TOP 1 DesignKey FROM @NewCDDesigns 
                                     WHERE [CurrentRow] = @counter)
    DECLARE @CurrentPreviousDesignKey INT = (SELECT TOP 1 DesignKey FROM @FBOMDesigns 
                                             WHERE ParentDesignKey =  (SELECT TOP 1 DesignKey FROM @NewCDDesigns WHERE [CurrentRow] = @counter))\
    EXEC [copyPreviousDesign]
        @DesignKey = @CurrentDesignKey  ,
        @PreviousDesignKey = @CurrentPreviousDesignKey

    EXEC [copyCustomersFromPreviousDesign]
        @DesignKey =@CurrentDesignKey ,
        @PreviousDesignKey = @CurrentPreviousDesignKey

    EXEC [addDefaultTasksToDesign]
        @DesignKey =  @CurrentDesignKey
END

问题是查询花费了太多时间,SQL Server Management Studio停留在第29分钟,我需要强制关闭。有什么方法可以更快地做到这一点?

1 个答案:

答案 0 :(得分:2)

您必须在while循环中增加@counter。这是一个无限循环。

选择@counter = @counter +1;