2016-08-23 93 views
0

我正在使用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 

回答

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 
+0

我試過這種方法。但是隨着這一點立即放緩。 – Hemal