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

后端 未结 4 2055
长情又很酷
长情又很酷 2020-11-30 05:17

I have a stored procedure that executes much faster from Sql Server Management Studio (2 seconds) than when run with System.Data.SqlClient.SqlCommand (times out

4条回答
  •  再見小時候
    2020-11-30 05:36

    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

提交回复
热议问题