2013-08-28 76 views
6

我面臨一個問題,MS SQL Server 2008的是:SQL Server查詢與參數需要更長的時間比常量字符串

當我使用硬編碼字符串作爲參數執行查詢,我的查詢運行快,但是當我使用字符串參數代替時,查詢需要更長的時間!
常量字符串查詢需要1秒,而另一個需要11秒。

這裏是波紋管的代碼:

常數串(1秒):

 SELECT * 
FROM VIEWCONTENTS 
WHERE COUNTRY = 'ZA' 
     AND CONTENTTYPE = 'A' 
     AND TASK = 'R23562'; 

參數(11秒):

DECLARE @country AS CHAR(2); 

SET @country = 'ZA'; 

SELECT * 
FROM VIEWCONTENTS 
WHERE COUNTRY = @country 
     AND CONTENTTYPE = 'A' 
     AND TASK = 'R23562' 
+3

谷歌「參數嗅探」... – granadaCoder

+2

你比較了執行計劃嗎?另請閱讀:http://www.sqlperformance.com/2013/08/t-sql-queries/parameter-sniffing-embedding-and-the-recompile-options –

+0

由於優化器不知道本地的值在第二個查詢中,它很可能會將查詢計劃更改爲使用表/索引掃描而不是查找。 – steoleary

回答

0

這是什麼產率?

DECLARE @country AS VARCHAR(2); 
SET @country = 'ZA'; 

SELECT * 
FROM VIEWCONTENTS 
WHERE COUNTRY = @country 
     AND CONTENTTYPE = 'A' 
     AND TASK = 'R23562' 

這個怎麼樣?

DECLARE @country AS CHAR(2); 
DECLARE @country1 AS VARCHAR(2); 
SET @country = 'ZA'; 
SET @country1 = @country; 

SELECT * 
FROM VIEWCONTENTS 
WHERE COUNTRY = @country 
     AND CONTENTTYPE = 'A' 
     AND TASK = 'R23562' 
2

使用OPTION(RECOMPILE)在查詢結束。所以:

DECLARE @country AS CHAR(2); 

SET @country = 'ZA'; 

SELECT * 
FROM VIEWCONTENTS 
WHERE COUNTRY = @country 
     AND CONTENTTYPE = 'A' 
     AND TASK = 'R23562' 
OPTION (RECOMPILE) 
相關問題