5

SQL 2008: This is slow (takes 1 1/2 minutes):

declare @p1 varchar(50)
set @p1 = '976j%'
select * from invsearch_query where comparepnfwd like @p1

This takes less than a second:

select * from invsearch_query where comparepnfwd like '976j%'

Why???

6
  • 1
    Take a look at the query execution plans (or post them here) Commented May 13, 2011 at 19:20
  • 1
    Try casting your literal to see if that makes any difference (CAST('976j%' AS VARCHAR(50))). Also, take a look at the execution plan to see the differences. Commented May 13, 2011 at 19:21
  • comparepnfwd is a varchar(50) Commented May 13, 2011 at 19:37
  • TAKES LESS THAN A SECOND: select * from invsearch_query where comparepnfwd like cast('976j%' as varchar(50)) Commented May 13, 2011 at 19:38
  • 1
    @Martin, yes you are right, the slow one was doing a clustered index scan on the main table (yes, invsearch_query was a view), and the fast one did index seeks and keylookups. Commented May 13, 2011 at 20:38

1 Answer 1

10

I would imagine that you must have a non covering index with leading column comparepnfwd that is used by the literal query but not by the query with the variable.

You can use OPTION (RECOMPILE) to get SQL Server to recompile the plan taking into account the actual variable value.

Sign up to request clarification or add additional context in comments.

1 Comment

option (recompile) made the 1st query as fast as the 2nd query. thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.