sql like query slow if using declare parameter but fast if not

点点圈 提交于 2019-12-10 16:54:47

问题


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:


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.



来源:https://stackoverflow.com/questions/5996713/sql-like-query-slow-if-using-declare-parameter-but-fast-if-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!