This is a odd problem where a bad plan was chosen again and again, but
then not.
Using the profiler, I identified an application-issued statement that
performed poorly. It took this form:
exec sp_executesql N'SELECT col1, col2 FROM t1 WHERE (t2= @Parm1)',
N'@Parm1 int', @Parm1 = 8609
t2 is a foreign key column, and is indexed.
I took the statement into query analyzer and executed it there. The
query plan showed that it was doing a scan of the primary key index,
which is clustered. That's a bad choice.
I then fiddled with it to see what would result in a good plan.
1) I changed it to hard code the query value (but with the parm
definition still in place. )
It performed well, using the correct index.
Here's how it looked.
exec sp_executesql N'SELECT cbord.cbo1013p_AZItemElement.AZEl_Intid AS
[Oid], cbord.cbo1013p_AZItemElement.incomplete_flag AS [IsIncomplete],
cbord.cbo1013p_AZItemElement.traceflag AS [IsTraceAmount],
cbord.cbo1013p_AZItemElement.standardqty AS [StandardAmount],
cbord.cbo1013p_AZItemElement.Uitem_intid AS [NutritionItemOid],
cbord.cbo1013p_AZItemElement.AZeldef_intid AS [AnalysisElementOid] FROM
cbord.cbo1013p_AZItemElement WHERE (Uitem_intid= 8609)', N'@Parm1 int',
@Parm1 = 8609
After doing this, re-executing the original form still gave bad
results.
2) I restored the use of the parm, but removed the 'exec' from the
start.
It performed well.
After that (surprise!) it also performed well in the original form.
What's going on here?