参数嗅探不起作用

时间:2016-08-23 06:36:58

标签: sql sql-server stored-procedures procedure procedures

我正在使用MSSQL。我有一个存储过程,可以在几天内正常工作,之后变得很慢。我开始知道参数嗅探将适用于它。实施之后,它永远变得缓慢。我也试过重新编译工作。我立即面临同样的缓慢问题。

有人可以帮我这个吗?

以下是我的存储过程的结构。

@START_VALUE int=null,
@END_VALUE int=null
@UID NVARCHAR(MAX)=null,
AS
BEGIN

SELECT
dbo.TABLE1.ID, 
ROW_NUMBER()  OVER (ORDER BY TABLE1.UPDATED_ON desc) AS RN,   
CONVERT(VARCHAR(10), dbo.TABLE1.DATE, 101) AS TDATE,
CATEGORY = (
        SELECT TOP 1 COLUMN1
        FROM TABLE5 CT1
        WHERE TABLE1.CATEGORY = CT1.CATEGORY_ID
   ), 
TYPETEXT = (
        SELECT TOP 1 COLUMN1
        FROM TABLE6 CT1
        WHERE TABLE1.TYPE = CT1.TYPE_ID
   ),
IMAGE = STUFF(( SELECT DISTINCT ',' + CAST(pm.C1 AS varchar(12))
                FROM TABLE2 pm
                WHERE pm.ID = TABLE1.ID AND pm.C1 IS NOT NULL AND pm.C1 <> '' 
                FOR XML PATH('')),
              1, 1, '' ) INTO #tempRecords       
FROM dbo.TABLE1 
WHERE ((@UID is null OR  dbo.TABLE1.ID = @UID )
ORDER BY TABLE1.UPDATED DESC      

SELECT @count = COUNT(*) FROM #tempRecords;

SELECT *, CONVERT([int],@count) AS 'TOTAL_RECORDS'
FROM #tempRecords 
WHERE #tempRecords.RN BETWEEN CONVERT([bigint], @START_VALUE) AND       CONVERT([bigint], @END_VALUE)      

 END

 GO

1 个答案:

答案 0 :(得分:0)

要使参数嗅探优化查询,请声明虚拟变量并在查询中使用它们,而不是使用原始参数。

CREATE PROCEDURE test_proc 
      @START_VALUE INT=NULL, 
      @END_VALUE   INT=NULL, 
      @UID         NVARCHAR(max)=NULL
    as 
      BEGIN 

        DECLARE @START_VALUE_SNIFF INT=NULL, 
        @END_VALUE_SNIFF   INT=NULL, 
        @UID_SNIFF         NVARCHAR(max)=NULL

        SET @START_VALUE_SNIFF = @START_VALUE
        SET @END_VALUE_SNIFF = @END_VALUE
        SET @UID_SNIFF = @UID

        select * from 
        FROM dbo.TABLE1 
        WHERE ((@UID_SNIFF  is null OR  dbo.TABLE1.ID = @UID_SNIFF )
        ORDER BY TABLE1.UPDATED DESC   

    END