Question

I just had a problem at work where a stored proc, being called by some C# code, was very slow. When I ran the same stored proc with the same parameters in Management Studio, it was very fast. After a little Googling, I followed the suggestion in this answer and it solved my problem.

I don't like fixing things without learning how they work, so I decided to read up on "parameter sniffing". My understanding is that SQL Server occasionally builds and caches an execution plan for the stored proc, and optimizes that plan based on whatever parameter values it happens to see at the time. So if you pass in different parameters later, you might get bad performance.

But in my case, I ran the stored proc with exactly the same parameter values from Management Studio and C#. Management Studio was fast, C# was slow. I would expect both to use the cached plan, so how could it be fast in one place and slow in another?

I unfortunately can't paste the code, but I can provide any additional details necessary. Just trying to understand this!

Was it helpful?

Solution

But in my case, I ran the stored proc with exactly the same parameter values from Management Studio and C#. Management Studio was fast, C# was slow. I would expect both to use the cached plan, so how could it be fast in one place and slow in another?

Welcome to parameter sniffing 🤣 It's not actually quite that simple.

It's possible that the SQL Server instance already had a compiled plan for the query when you ran your test, that was compiled for different parameters. If this is a test system, and you won't be disrupting others, you could run DBCC FREEPROCCACHE on the instance to make sure you don't have any cached plans before running your test.

There could even be more than one plan depending on whether whitespace, capitalization, SET options, etc were different between the C# batch and the one you ran in SSMS (See Aaron Bertrand's post Multiple Plans for an "Identical" Query for details). You can use the queries in Aaron's post to see if you have different plans for the C# code version and the SSMS version. Then you could compare them (in particular the SET options and the queryhash, both of which can be found by right-clicking on the SELECT operator in the plan and going to "Properties") to see what's different.

For an extremely detailed treatment on this issue, see Slow in the Application, Fast in SSMS? by Erland Sommarskog. There's also a great resource on this site for identifying and troubleshooting the issue by Erik Darling here on the site: Why is my query suddenly slower than it was yesterday?

I hope that helps! Let me know if you're still lost after reading those resources, it can all be a little confusing.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top