SQL Server query takes longer with parameter than with constant string

I had a problem with MS SQL Server 2008, which:

When I execute a query using a hard-coded string as a parameter, my query is fast, but when I use a string parameter, the query takes longer!
A constant string query takes 1 second and another 11 seconds.

Here are the codes below:

Permanent line (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' 
+6
source share
2 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) 
+2
source

What does it give?

 DECLARE @country AS VARCHAR(2); SET @country = 'ZA'; SELECT * FROM VIEWCONTENTS WHERE COUNTRY = @country AND CONTENTTYPE = 'A' AND TASK = 'R23562' 

How about this?

 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' 
0
source

Source: https://habr.com/ru/post/952682/


All Articles