Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server query takes longer with parameter than with constant string

I'm facing a problem with MS SQL Server 2008 which is:

When I execute a query using a hard-coded string as a parameter, my query run fast but when I use a string parameter instead, the query takes longer!
Constant string query takes 1 second while the other takes 11 seconds.

Here are the codes bellow:

Constant string (1 second):

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

Parameterized (11 seconds):

DECLARE @country AS CHAR(2); 

SET @country = 'ZA'; 

SELECT * 
FROM   VIEWCONTENTS 
WHERE  COUNTRY = @country 
       AND CONTENTTYPE = 'A' 
       AND TASK = 'R23562' 
like image 221
Gabriel Avatar asked Aug 28 '13 19:08

Gabriel


1 Answers

Use OPTION (RECOMPILE) at the end of your query. So:

DECLARE @country AS CHAR(2); 

SET @country = 'ZA'; 

SELECT * 
FROM   VIEWCONTENTS 
WHERE  COUNTRY = @country 
       AND CONTENTTYPE = 'A' 
       AND TASK = 'R23562'
OPTION (RECOMPILE)
like image 195
ninjaPixel Avatar answered Oct 16 '22 23:10

ninjaPixel