sql like query slow if using declare parameter but

2019-06-24 00:03发布

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???

1条回答
SAY GOODBYE
2楼-- · 2019-06-24 00:39

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.

查看更多
登录 后发表回答