7

我遇到了 MS SQL Server 2008 的问题,即:

当我使用硬编码字符串作为参数执行查询时,我的查询运行得很快,但是当我使用字符串参数时,查询需要更长的时间!
常量字符串查询需要 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' 
4

2 回答 2

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)
于 2013-10-23T13:20:29.230 回答
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' 
于 2013-08-29T04:11:17.140 回答