SQL Server查询使用参数比使用常量字符串花费更长时间

时间:2013-08-28 19:05:27

标签: sql-server performance parameters database-performance

我遇到了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' 

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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'