我的存储过程太慢了

时间:2017-11-26 07:25:36

标签: sql-server stored-procedures

我的存储过程太慢了。我可以加快速度吗?

ALTER PROCEDURE [dbo].[CalBuyAvg]
    @companyCode INT
AS
BEGIN
    BEGIN TRANSACTION CalBuyAvg

    DELETE FROM dbo.tmpCalSood 
    WHERE CompanyCode = @companyCode

    DECLARE @id INT
    DECLARE @previd INT
    DECLARE @prvBuyAvg DECIMAL(18,0)
    DECLARE @prvKcode INT

    DECLARE db_cursor CURSOR FOR  
         SELECT Id, LAG(Id) OVER (ORDER BY kalaCode, Tarikh, id) prevId
         FROM dbo.CalMandeVW
         ORDER BY kalaCode, Tarikh, id

    OPEN db_cursor   

    FETCH NEXT FROM db_cursor INTO @id, @previd   

    WHILE @@FETCH_STATUS = 0   
    BEGIN   
        SELECT @prvKcode = KalaCode, @prvBuyAvg = buyAvg
        FROM dbo.TmpCalSood 
        WHERE id = @previd

        INSERT INTO dbo.TmpCalSood ([Id], [Tarikh], [KalaCode], [kalaType], [Varede], [fiVarede], [SumVarede], 
                                    SaleMali, AnbarCode, pType, pCode, ProjectCode, CompanyCode, 
                                    Sadere, fiSadere, SumSadere, Mandeh, LastMande , buyavg) 
            SELECT 
                [Id], [tarikh], [KalaCode], 0, [Varede], [fiVarede], [sumVarede],
                SaleMali, AnbarCode, pType, pCode, ProjectCode, CompanyCode, 
                Sadere, fiSadere, SumSadere, Mandeh, lastMande, 
                CASE 
                   WHEN lastMande = 0 
                      THEN dbo.CalMandeVW.fiVarede 
                      ELSE  
                         CASE 
                            WHEN varede = 0 
                               THEN 
                                  CASE 
                                     WHEN @prvKcode = kalaCode 
                                        THEN @prvBuyAvg 
                                        ELSE 0 
                                  END
                               ELSE 
                                  CASE 
                                     WHEN @prvKcode = kalaCode 
                                        THEN ((sumVarede) + (LastMande*@prvBuyAvg)) / (varede+lastMande)
                                        ELSE dbo.CalMandeVW.fiVarede 
                                  END
                         END
                END AS newbuyAvg
            FROM 
                dbo.CalMandeVW 
            WHERE 
                id = @id

        FETCH NEXT FROM db_cursor INTO @id, @previd
    END   

    CLOSE db_cursor   
    DEALLOCATE db_cursor;

    COMMIT
    RETURN 1
END

1 个答案:

答案 0 :(得分:0)

游标是性能杀手。 使用

INSERT...INTO....SELECT

更好性能的语法