Query runs fast, but runs slow in stored procedure

后端 未结 6 393
遥遥无期
遥遥无期 2020-12-04 16:52

I am doing some tests using the SQL 2005 profiler.

I have a stored procedure which simply runs one SQL query.

When I run the stored procedure, it takes a lon

相关标签:
6条回答
  • 2020-12-04 17:12

    OK, we have had similar issues like this before.

    The way we fixed this, was by making local parameters inside the SP, such that

    DECLARE @LOCAL_Contract_ID int, 
            @LOCAL_dt_From smalldatetime, 
            @LOCAL_dt_To smalldatetime, 
            @LOCAL_Last_Run_Date datetime
    
    SELECT  @LOCAL_Contract_ID = @Contract_ID, 
            @LOCAL_dt_From = @dt_From, 
            @LOCAL_dt_To = @dt_To, 
            @LOCAL_Last_Run_Date = @Last_Run_Date
    

    We then use the local parameters inside the SP rather than the parameters that was passed in.

    This typically fixed the issue for Us.

    We believe this to be due to parameter sniffing, but do not have any proof, sorry... X-)

    EDIT:

    Have a look at Different Approaches to Correct SQL Server Parameter Sniffing for some insightful examples, explanations and fixes.

    0 讨论(0)
  • 2020-12-04 17:13

    The issue of why a batch takes forever to run inside a SQL stored procedure yet runs instantaneously in SSMS has to do with SQL parameter sniffing, especially with datetime parameters.

    There are several excellent articles on parameter sniffing out there.

    Here's one of them ( I didn't write it, just passing it on).

    http://www.sommarskog.se/query-plan-mysteries.html

    0 讨论(0)
  • 2020-12-04 17:20

    As others have mentioned, this could be a 'parameter sniffing' problem. Try including the line:

    OPTION (RECOMPILE)
    

    at the end of your SQL query.

    There is an article here explaining what parameter sniffing is: http://blogs.technet.com/b/mdegre/archive/2012/03/19/what-is-parameter-sniffing.aspx

    0 讨论(0)
  • 2020-12-04 17:20

    I too got the same problem today. I have dropped and recreated the SP and it worked. This is something with SP cache and when dropped the SP the cached plan has been removed. You can try the same or use 'DBCC FREEPROCCACHE' to delete cache.

    0 讨论(0)
  • 2020-12-04 17:30

    On my issue I've run:

    exec sp_updatestats 
    

    and this speed up my sp from 120s to just 3s. More info about Updating Statistics can be found here https://msdn.microsoft.com/en-us/library/ms173804.aspx

    0 讨论(0)
  • 2020-12-04 17:35

    I guess this is caused by parameter sniffing.

    0 讨论(0)
提交回复
热议问题