开发者

Why does the parameterized version of this query run slower than a non-parameterized version?

开发者 https://www.devze.com 2023-01-20 16:26 出处:网络
Sample Query: CREATE PROCEDURE dbo.Test (@p varchar(10)) AS DECLARE @param varchar(10) SET @param = @p + \'%\'

Sample Query:

CREATE PROCEDURE dbo.Test (@p varchar(10))
AS
DECLARE @param varchar(10)
SET @param = @p + '%'

SELECT * FROM table1 t1
INNER JOIN table2 t2 on t1.id = tr.id
WHERE t2.desc LIKE @param

I've a query which is similar to one above and when i use this in stored procedure it runs indefinitely without giving any output. But if i use same query as,

SELECT * FROM table1 t1
INNER JOIN table2 t2 on t开发者_StackOverflow社区1.id = tr.id
WHERE t2.desc LIKE 'A%'  -- notice no parameter here

This executes in less than a second.

My table2 has 140K records and table1 some 250K

Any idea what could be causing like operator to run slow?


It does not know at compile time that @param will not have a leading wildcard so when it compiles the batch it gives you a plan with a scan not a seek.

You could maybe try OPTION (RECOMPILE) or OPTION (FORCESEEK) (SQL Server 2008) to see if it gives you a better plan.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号