In a SQL Server 2005 database I'm working on this query:
select *
from foo
join bar on bar.x = foo.x
join baz on baz.y = foo.y
where foo.x = 1000
has a vastly different and faster query plan than the following parameterized version.
declare @p0 int
set @p0 = 1000
select *
from foo
join bar on bar.x = foo.x
join baz on baz.y = foo.y
where foo.x = @p0
In my particular case the version with the literal runs in sub-second time. The parameterized version takes 2-3 seconds. I expected them to be identical given that they're the same query.
Why are they getting different query plans?
Is there any way to make the parameterized version have the same performance as the literal version?
Here are the query plans. My real query is rather different than the generic one I gave above, however the ONLY difference between the two queries that produced these plans is the parameter. Why would replacing a literal with a parameter result in such vastly different plans?