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