Why is some sql query much slower when used with SqlCommand?

♀尐吖头ヾ 提交于 2019-11-27 04:05:57

Another thing that can be important is the SET options that are enabled. Some of these options change the query plan sufficiently to change the profile. Some can have a huge impact if you are looking at (for example) a calculated + persisted (and possibly indexed) column: if the SET options aren't compatible, it can be forced to re-calculate the values, rather than using the indexed value - which can change an index seek into a table scan + calculation.

Try using the profiler to see what SET options are "in play", and see if using those options changes things.

Another impact is the connection string; for example, if you enable MARS that can change the behaviour in subtle ways.

Finally, transactions (implicit (TransactionScope) or explicit) can have a huge impact, depending on the isolation level.

Mitch Wheat

This is almost certainly due to an 'incorrect' cached query plan. This has come up on SO quite a few times.

Do you have up-to-date statistics? A regular scheduled index maintenance plan?

You can test if it is definitely due to the cached query plan by adding this to your stored procedure definition:

CREATE PROCEDURE usp_MyProcedure WITH RECOMPILE...

This will re-index an entire database (caution if database is very large!):

exec sp_msforeachtable "dbcc dbreindex('?')"

SO posts:

Big difference in execution time of stored proc between Managment Studio and TableAdapter.

Parameter Sniffing (or Spoofing) in SQL Server

optimize for unknown for SQL Server 2005?

Different Execution Plan for the same Stored Procedure

Had a similar issue and it turns out having MultipleActiveResultSets=true in the connection string (which is supposed to have minimal impact) was making pulling 1.5mil records over a remote connection take 25 minutes instead of around 2 minutes.

We had a similiar issue, where a query would complete in 2 seconds in SSMS and take more than 90 seconds when called from a .NET client (we wrote several VB/C# apps/sites to test it.)

We suspected that the query plan would be different, and rewrote the query with explicit looping ("inner loop join" and "with index") hints. This solved the problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!