SQL相同的精确查询第一次运行很快,而第二次运行慢。然后交替

时间:2019-09-24 17:23:26

标签: sql sql-server query-optimization

我有一个查询。当我第一次运行它时,它会立即返回。大约一秒钟。然后,当我按F5键再次运行完全相同的东西而没有任何更改时,现在它运行缓慢,耗时超过30秒。然后,如果我再次按下F5,它将再次立即运行。依此类推,并且保持交替。

以下是查询:

IF @LocalDetailLevel = 'master'
BEGIN

    SELECT * FROM (
        SELECT DISTINCT

        Master_Item
        ,'--' Item_Number
        ,'--' Color_Code 
        ,Description
        ,'--' Color_Description

        ,SUM(Unit_Retail) Sum_Unit_Retail
        ,AVG(Unit_Retail)  Avg_Unit_Retail

        ,SUM(Unit_MarkDown)  Sum_Unit_MarkDown
        ,AVG(Unit_MarkDown)  Avg_Unit_MarkDown
        ,AVG(Unit_MarkDown_Percent)  Avg_Unit_MarkDown_Percent

        ,SUM(Sell_Price)  Sum_Sell_Price
        ,AVG(Sell_Price)  Avg_Sell_Price

        ,SUM(Discount_Value)  Sum_Discount_Value
        ,AVG(Discount_Value)  Avg_Discount_Value
        ,AVG(Unit_Discount_Value_Percent)  Avg_Discount_Value_Percent

        ,SUM(Sale_Price)  Sum_Sale_Price
        ,AVG(Sale_Price)  Avg_Sale_Price

        ,SUM(Royalty_Cost)  Sum_Royalty_Cost
        ,AVG(Royalty_Cost)  Avg_Royalty_Cost
        ,AVG(Unit_Royalty_Cost_Percent)  Avg_Royalty_Cost_Percent

        ,SUM(Item_Cost)  Sum_Item_Cost
        ,AVG(Item_Cost)  Avg_Item_Cost
        ,AVG(Unit_Item_Cost_Percent)  Avg_Item_Cost_Percent

        ,SUM(Order_Gross_Profit_Minus_Discounts_And_Royalty_And_Freight)  Sum_Gross_Profit
        ,AVG(Order_Gross_Profit_Minus_Discounts_And_Royalty_And_Freight)  Avg_Gross_Profit
        ,AVG(Order_Gross_Profit_Minus_Discounts_And_Royalty_And_Freight_Percent)  Avg_Gross_Profit_Percent

        ,MAX(Quantity_Invoiced+Quantity_Allocated)  Max_Quantity

        ,SUM(Quantity_Invoiced+Quantity_Allocated)  Total_Units

        ,COUNT(DISTINCT Customer_Purchase_Order_Number ) Total_Orders_Cont
        ,-1 Percent_Of_Orders_Cont

        ,SUM(Quantity_Invoiced+Quantity_Allocated) / COUNT(DISTINCT Customer_Purchase_Order_Number) Average_Order_Quantity

        ,SUM(Quantity_Returned)  Total_Units_Returned
        ,MAX(Quantity_Returned)  Max_Quantity_Returned
        ,SUM(Quantity_Returned)  
        /NULLIF(SUM(Quantity_Invoiced+Quantity_Allocated) ,0) Return_Percentage

        ,SUM(CASE WHEN F.Line_Status = 'CANCELLED' THEN Quantity_Ordered ELSE 0 END)  Cancelled_Count
        ,SUM(CASE WHEN F.Line_Status = 'CANCELLED' THEN Quantity_Ordered ELSE 0 END)  
        / NULLIF(SUM(Quantity_Ordered) ,0) Cancelled_Count_Percent

        ,SUM(CASE WHEN (Tags not like '%customerrequested_cancel%' and Tags not like '%ia_cancel%' and (FulfillmentState like 'partial%' or FinancialState like 'partial%')) THEN Short_Shipped ELSE 0 END)  Short_Shipped_Count
        ,SUM(CASE WHEN (Tags not like '%customerrequested_cancel%' and Tags not like '%ia_cancel%' and (FulfillmentState like 'partial%' or FinancialState like 'partial%')) THEN Short_Shipped ELSE 0 END)  
        / NULLIF(SUM(Quantity_Ordered) ,0) Short_Shipped_Count_Percent

    FROM 
        FinalEcomTable F

    WHERE
        1=1
        AND (F.Company_Code = @LocalCompanyCode OR @LocalCompanyCode IS NULL)  
        AND (F.Division_Code = @LocalDivisionCode OR @LocalDivisionCode IS NULL)
        AND F.Coal_Date BETWEEN @LocalFromDate AND DATEADD(dayofyear, 1, @LocalToDate)

    GROUP BY Master_Item, Item_Number, Color_Code, Description, Color_Description


    ) T

    ORDER BY  
        CASE WHEN @LocalOrderBy = 'ordered' THEN Total_Units END DESC, 
        CASE WHEN @LocalOrderBy = 'returned' THEN Total_Units_Returned END DESC,
        CASE WHEN @LocalOrderBy = 'cancelled' THEN Cancelled_Count END DESC,
        CASE WHEN @LocalOrderBy = 'shortshipped' THEN Short_Shipped_Count END DESC

    --OPTION    (RECOMPILE)

END

IF @LocalDetailLevel = 'size'
BEGIN

    SELECT * FROM (
        SELECT DISTINCT

        Master_Item
        ,Item_Number
        ,'--' Color_Code 
        ,Description
        ,'--' Color_Description
        ,SUM(Unit_Retail)  Sum_Unit_Retail
        ,AVG(Unit_Retail)  Avg_Unit_Retail

        ,SUM(Unit_MarkDown)  Sum_Unit_MarkDown
        ,AVG(Unit_MarkDown)  Avg_Unit_MarkDown
        ,AVG(Unit_MarkDown_Percent)  Avg_Unit_MarkDown_Percent

        ,SUM(Sell_Price)  Sum_Sell_Price
        ,AVG(Sell_Price)  Avg_Sell_Price

        ,SUM(Discount_Value)  Sum_Discount_Value
        ,AVG(Discount_Value)  Avg_Discount_Value
        ,AVG(Unit_Discount_Value_Percent)  Avg_Discount_Value_Percent

        ,SUM(Sale_Price)  Sum_Sale_Price
        ,AVG(Sale_Price)  Avg_Sale_Price

        ,SUM(Royalty_Cost)  Sum_Royalty_Cost
        ,AVG(Royalty_Cost)  Avg_Royalty_Cost
        ,AVG(Unit_Royalty_Cost_Percent)  Avg_Royalty_Cost_Percent

        ,SUM(Item_Cost)  Sum_Item_Cost
        ,AVG(Item_Cost)  Avg_Item_Cost
        ,AVG(Unit_Item_Cost_Percent)  Avg_Item_Cost_Percent

        ,SUM(Order_Gross_Profit_Minus_Discounts_And_Royalty_And_Freight)  Sum_Gross_Profit
        ,AVG(Order_Gross_Profit_Minus_Discounts_And_Royalty_And_Freight)  Avg_Gross_Profit
        ,AVG(Order_Gross_Profit_Minus_Discounts_And_Royalty_And_Freight_Percent)  Avg_Gross_Profit_Percent

        ,MAX(Quantity_Invoiced+Quantity_Allocated)  Max_Quantity

        ,SUM(Quantity_Invoiced+Quantity_Allocated)  Total_Units

        ,COUNT(DISTINCT Customer_Purchase_Order_Number) Total_Orders_Cont
        ,-1 Percent_Of_Orders_Cont

        ,SUM(Quantity_Invoiced+Quantity_Allocated) / COUNT(DISTINCT Customer_Purchase_Order_Number) Average_Order_Quantity

        ,SUM(Quantity_Returned)  Total_Units_Returned
        ,MAX(Quantity_Returned)  Max_Quantity_Returned
        ,SUM(Quantity_Returned)  
        /NULLIF(SUM(Quantity_Invoiced+Quantity_Allocated) ,0) Return_Percentage

        ,SUM(CASE WHEN F.Line_Status = 'CANCELLED' THEN Quantity_Ordered ELSE 0 END)  Cancelled_Count
        ,SUM(CASE WHEN F.Line_Status = 'CANCELLED' THEN Quantity_Ordered ELSE 0 END)  
        / NULLIF(SUM(Quantity_Ordered) ,0) Cancelled_Count_Percent

        ,SUM(CASE WHEN (Tags not like '%customerrequested_cancel%' and Tags not like '%ia_cancel%' and (FulfillmentState like 'partial%' or FinancialState like 'partial%')) THEN Short_Shipped ELSE 0 END)  Short_Shipped_Count
        ,SUM(CASE WHEN (Tags not like '%customerrequested_cancel%' and Tags not like '%ia_cancel%' and (FulfillmentState like 'partial%' or FinancialState like 'partial%')) THEN Short_Shipped ELSE 0 END)  
        / NULLIF(SUM(Quantity_Ordered) ,0) Short_Shipped_Count_Percent


    FROM 
        FinalEcomTable F

    WHERE
        1=1
        AND (F.Company_Code = @LocalCompanyCode OR @LocalCompanyCode IS NULL)  
        AND (F.Division_Code = @LocalDivisionCode OR @LocalDivisionCode IS NULL)
        AND F.Coal_Date BETWEEN @LocalFromDate AND DATEADD(dayofyear, 1, @LocalToDate)

    GROUP BY Master_Item, Item_Number, Color_Code, Description, Color_Description

    ) T

    ORDER BY  
        CASE WHEN @LocalOrderBy = 'ordered' THEN Total_Units END DESC, 
        CASE WHEN @LocalOrderBy = 'returned' THEN Total_Units_Returned END DESC,
        CASE WHEN @LocalOrderBy = 'cancelled' THEN Cancelled_Count END DESC,
        CASE WHEN @LocalOrderBy = 'shortshipped' THEN Short_Shipped_Count END DESC

    --OPTION    (RECOMPILE)

END

IF @LocalDetailLevel = 'color'
BEGIN

    SELECT * FROM (
        SELECT DISTINCT

        Master_Item
        ,Item_Number
        ,Color_Code 
        ,Description
        ,Color_Description
        ,SUM(Unit_Retail)  Sum_Unit_Retail
        ,AVG(Unit_Retail)  Avg_Unit_Retail

        ,SUM(Unit_MarkDown)  Sum_Unit_MarkDown
        ,AVG(Unit_MarkDown)  Avg_Unit_MarkDown
        ,AVG(Unit_MarkDown_Percent)  Avg_Unit_MarkDown_Percent

        ,SUM(Sell_Price)  Sum_Sell_Price
        ,AVG(Sell_Price)  Avg_Sell_Price

        ,SUM(Discount_Value)  Sum_Discount_Value
        ,AVG(Discount_Value)  Avg_Discount_Value
        ,AVG(Unit_Discount_Value_Percent)  Avg_Discount_Value_Percent

        ,SUM(Sale_Price)  Sum_Sale_Price
        ,AVG(Sale_Price)  Avg_Sale_Price

        ,SUM(Royalty_Cost)  Sum_Royalty_Cost
        ,AVG(Royalty_Cost)  Avg_Royalty_Cost
        ,AVG(Unit_Royalty_Cost_Percent)  Avg_Royalty_Cost_Percent

        ,SUM(Item_Cost)  Sum_Item_Cost
        ,AVG(Item_Cost)  Avg_Item_Cost
        ,AVG(Unit_Item_Cost_Percent)  Avg_Item_Cost_Percent

        ,SUM(Order_Gross_Profit_Minus_Discounts_And_Royalty_And_Freight)  Sum_Gross_Profit
        ,AVG(Order_Gross_Profit_Minus_Discounts_And_Royalty_And_Freight)  Avg_Gross_Profit
        ,AVG(Order_Gross_Profit_Minus_Discounts_And_Royalty_And_Freight_Percent)  Avg_Gross_Profit_Percent

        ,MAX(Quantity_Invoiced+Quantity_Allocated)  Max_Quantity

        ,SUM(Quantity_Invoiced+Quantity_Allocated)  Total_Units

        ,COUNT(DISTINCT Customer_Purchase_Order_Number) Total_Orders_Cont
        ,-1 Percent_Of_Orders_Cont

        ,SUM(Quantity_Invoiced+Quantity_Allocated) / COUNT(DISTINCT Customer_Purchase_Order_Number) Average_Order_Quantity

        ,SUM(Quantity_Returned)  Total_Units_Returned
        ,MAX(Quantity_Returned)  Max_Quantity_Returned
        ,SUM(Quantity_Returned)  
        /NULLIF(SUM(Quantity_Invoiced+Quantity_Allocated) ,0) Return_Percentage

        ,SUM(CASE WHEN F.Line_Status = 'CANCELLED' THEN Quantity_Ordered ELSE 0 END)  Cancelled_Count
        ,SUM(CASE WHEN F.Line_Status = 'CANCELLED' THEN Quantity_Ordered ELSE 0 END)  
        / NULLIF(SUM(Quantity_Ordered) ,0) Cancelled_Count_Percent

        ,SUM(CASE WHEN (Tags not like '%customerrequested_cancel%' and Tags not like '%ia_cancel%' and (FulfillmentState like 'partial%' or FinancialState like 'partial%')) THEN Short_Shipped ELSE 0 END)  Short_Shipped_Count
        ,SUM(CASE WHEN (Tags not like '%customerrequested_cancel%' and Tags not like '%ia_cancel%' and (FulfillmentState like 'partial%' or FinancialState like 'partial%')) THEN Short_Shipped ELSE 0 END)  
        / NULLIF(SUM(Quantity_Ordered) ,0) Short_Shipped_Count_Percent

    FROM 
        FinalEcomTable F

    WHERE
        1=1
        AND (F.Company_Code = @LocalCompanyCode OR @LocalCompanyCode IS NULL)  
        AND (F.Division_Code = @LocalDivisionCode OR @LocalDivisionCode IS NULL)
        AND F.Coal_Date BETWEEN @LocalFromDate AND DATEADD(dayofyear, 1, @LocalToDate)

    GROUP BY Master_Item, Item_Number, Color_Code, Description, Color_Description

    ) T

    ORDER BY  
        CASE WHEN @LocalOrderBy = 'ordered' THEN Total_Units END DESC, 
        CASE WHEN @LocalOrderBy = 'returned' THEN Total_Units_Returned END DESC,
        CASE WHEN @LocalOrderBy = 'cancelled' THEN Cancelled_Count END DESC,
        CASE WHEN @LocalOrderBy = 'shortshipped' THEN Short_Shipped_Count END DESC

    --OPTION    (RECOMPILE)

END

我假设这与编译器试图优化我的查询有关。我该如何使它针对“ @LocalDetailLevel ='color'”进行优化,因为这将在90%的时间内使用?

如果有人可以告诉我如何添加

OPTION (OPTIMIZE FOR (@LocalDetailLevel = 'color'))

对于我的存储过程,我认为这可以解决很多问题。我的存储过程是

GO
/****** Object:  StoredProcedure [dbo].[Z_N_FinalEcomDashAllItems]    Script Date: 9/24/2019 12:20:31 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROC [dbo].[ZZ_N_FinalEcomDashAllItems] 

@CompanyCode    VARCHAR(5),
@DivisionCode   VARCHAR(5),
@FromDate       DATETIME,
@ToDate         DATETIME,
@DetailLevel    VARCHAR(50),
@OrderBy    VARCHAR(50)


AS

DECLARE @LocalCompanyCode VARCHAR(5)
SET @LocalCompanyCode = @CompanyCode

DECLARE @LocalDivisionCode VARCHAR(5)
SET @LocalDivisionCode = @DivisionCode

DECLARE @LocalFromDate DATETIME
SET @LocalFromDate = @FromDate

DECLARE @LocalToDate DATETIME
SET @LocalToDate = @ToDate

DECLARE @LocalDetailLevel VARCHAR(50)
SET @LocalDetailLevel = @DetailLevel

DECLARE @LocalOrderBy VARCHAR(50)
SET @LocalOrderBy = @OrderBy

BEGIN
... The query from above
END

我试图这样添加它

BEGIN
... The query from above
OPTION (OPTIMIZE FOR (@LocalDetailLevel = 'color'))
END

但是它说“关键字'OPTION'附近的语法不正确。”

如果我删除了IF子句之后的所有BEGIN / END,并且在整个过程中只有一个开始结束,那么我会在OPTIMIZE FOR子句中指定“变量” @LocalDetailLevel”,但未使用在查询中。”

0 个答案:

没有答案