Question

I have the following "identical" queries:

select * from myView where ID=1

and

declare @ID int
set @ID=1
select * from myView where ID=@ID

myView is a view(not indexed view) with a couple of inner and outer joins. The unfiltered output of the view is @100 mil rows. For ID=1 the output is @10k rows. The first query returns in a couple of seconds and the other query runs for hours. They seem "identical", but apparently behind the scenes (when looking at the execution plan) I can derive the fact that the filtering on the view in the second script is only applied at the end, after the whole view is queried. Why is this happening or does anyone have a better and clearer explanation for this?

Later edit: Kevchadders's suggestion was very useful. By looking at this article: http://blogs.msdn.com/b/turgays/archive/2013/09/10/parameter-sniffing-problem-and-workarounds.aspx I was able to use the following workaround for the second script, that "solved the problem":

declare @ID int
set @ID=1
select * from myView where ID=@ID
option(recompile)
Was it helpful?

Solution

This could to be due to parameter sniffing.

The execution plan might not be identical for both so even though your are running what looks like identical code, sql server will be taking a different execution route for each piece of SQL.

It might be worth taking a look at there respective execution plan to see if you can spot any differences. As per the question using OPTION(RECOMPILE).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top