虽然循环会花费太多时间,但可以对其进行优化吗?

时间:2019-02-22 10:50:49

标签: sql-server

我的may表中有80,000行,基于此,我必须预测直到退休前的贡献,执行查询时大约需要20分钟才能完成。如何优化查询?

declare @Max as int
    declare @Kount as int
        Set @Kount = 1
        SELECT row_number() Over (order by PRAN) as row,
        PRAN, emp_cont, dob, doj_govt, dor,[100 sal],[BP+GP],nps14
        into #rawdata1
        FROM npst
        order by PRAN 

        set @Max = (Select Max(row) from #rawdata1)
        Create Table #Rawdata2
          (
             [Row] int,
            PRAN float,
           emp_cont float,
            dob datetime, 
            doj_govt datetime, 
            dor datetime,
            [100 sal] float,
            [BP+GP] float,
            nps14 float,
            CalAmt float,       
          ) 

        while (@kount <= @max)
        BEGIN
         DECLARE @PRAN float
         SELECT @PRAN  = (PRAN) FROM #rawdata1  where row=@Kount
         DECLARE  @SER_LEFT INT 
         SELECT @SER_LEFT= (DATEDIFF(YEAR,GETDATE(),dor)) from #rawdata1 where row=@Kount
         DECLARE @NPS NUMERIC (10,2)
         SELECT @NPS= nps14 from #rawdata1 where row=@Kount
         DECLARE @I AS INT
         SET @I=1
            WHILE @I<@SER_LEFT
            BEGIN
             SET @NPS=(0.03*@NPS)+@NPS
             SET @I=@I+1
            END
   INSERT INTO #rawdata2
         SELECT @Kount as Row, PRAN, emp_cont, dob, doj_govt, dor,[100 sal],[BP+GP],nps14, @NPS  FROM #rawdata1
           WHERE PRAN=@PRAN
        SET @Kount = @Kount + 1
    END

1 个答案:

答案 0 :(得分:-1)

您需要在#Rawdata1上创建索引,以便SQL Server可以在每次查找一行并更新一行时使用搜索而不是扫描。我会先在“行”列上创建聚簇索引(这是在临时表上创建索引的唯一方法),然后在“ PRAN”列上创建另一个索引。

为什么语句中括号内是PRAN?

public static final Date FINISHING_TIME = "FinishingTime"