Slow SP with date parameters solved.

  • Comments posted to this topic are about the item Slow SP with date parameters solved.

  • .

  • I don't understand the problem you are trying to solve.

    Is it a parameterization issue?

    Ditto previous comment i.e what sql version have you found this to be an issue on?

    How large were your tables? Were they indexed? Did you look at the execution plan to analyse what was going on?

  • I checked it on 1030484 rows and in my case it worked the same when I run it from direct query and from a SP

  • Starting from sql2000 sp4 and sql2005, sql2008, the optimizer changed strategy to retrieve data when you specify parameters in the where clause. So, in this case "column1 between @from and @to" for the optimizer means "read all rows" and starts with a full scan table instead of using index. Another solution is using hints and force the use of index:

    select * from tab with(index(idx_tab)) where column1 between @from and @to

  • Not very scientific, but I found that the first time I ran, the result from the @tableparams was considerably faster when selecting approx 17,000 rows from 682,000, where there is no useful index.

    (17234 row(s) affected)

    SQL Server Execution Times:

    CPU time = 2250 ms, elapsed time = 8095 ms.

    -- this one was parameterised

    (17234 row(s) affected)

    SQL Server Execution Times:

    CPU time = 515 ms, elapsed time = 1784 ms.

    -- this using the table variable

    Running exactly the same thing a second time the difference was greatly reduced.

    (17234 row(s) affected)

    SQL Server Execution Times:

    CPU time = 343 ms, elapsed time = 958 ms.

    (17234 row(s) affected)

    SQL Server Execution Times:

    CPU time = 314 ms, elapsed time = 264 ms.

    Using a different table, the paraemterised query was quicker on the second run.

  • I've run across this problem several times as well.

    I try copying the parameters into local variables, then use the local variables in the WHERE clause.

    That almost always fixes the problem.

    The two result in very different execution plans, though I've never really understood why.

    I'd love to hear what is going on behind the scenes.

  • It might be parameter sniffing. If you do what Christopher suggested this will resolve the issue with parameter sniffing. I think there are other ways to resolve the issue as well, but don't recall them right now. Just google parameter sniffing.

  • On the subject of parameter sniffing, here's a good article that describes how that works (and best of all, how it can go wrong!)

  • I had this same problem. I simply copied the code in the SPROC and then dropped the object. Lastly, I recreated the SPROC and everything ran fine.

  • Thanks for the script.

Viewing 11 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic. Login to reply