Why execute stored procedures is faster than SQL query from a script?

前端 未结 8 2069
别那么骄傲
别那么骄傲 2020-11-30 03:31

In fact, if I call the stored procedures from my application, I need a connection to my DB.

So, why calling a \"stored procedures\" should be faster than \"passing a

相关标签:
8条回答
  • 2020-11-30 04:06

    SQL Server basically goes through these steps to execute any query (stored procedure call or ad-hoc SQL statement):

    1) syntactically check the query
    2) if it's okay - it checks the plan cache to see if it already has an execution plan for that query
    3) if there is an execution plan - that plan is (re-)used and the query executed
    4) if there is no plan yet, an execution plan is determined
    5) that plan is stored into the plan cache for later reuse
    6) the query is executed

    The point is: ad-hoc SQL and stored procedures are treatly no differently.

    If an ad-hoc SQL query is properly using parameters - as it should anyway, to prevent SQL injection attacks - its performance characteristics are no different and most definitely no worse than executing a stored procedure.

    Stored procedure have other benefits (no need to grant users direct table access, for instance), but in terms of performance, using properly parametrized ad-hoc SQL queries is just as efficient as using stored procedures.

    Update: using stored procedures over non-parametrized queries is better for two main reasons:

    • since each non-parametrized query is a new, different query to SQL Server, it has to go through all the steps of determining the execution plan, for each query (thus wasting time - and also wasting plan cache space, since storing the execution plan into plan cache doesn't really help in the end, since that particular query will probably not be executed again)

    • non-parametrized queries are at risk of SQL injection attack and should be avoided at all costs

    0 讨论(0)
  • 2020-11-30 04:07

    Unlike standard SQL statements, stored procedures are compiled and optimized by the database server. This optimization involves using information about the structure of a particular database that's required at execution time by the stored procedure. This process of storing execution information (the execution plan) is a tremendous time saver, especially if the stored procedure is called many times.

    Speed is also improved by the fact that stored procedures run entirely on the database server - there's no need to pass large chunks of SQL code over a network. For a simple SELECT statement, that might not make a big difference, but in cases where we perform a series of loops and calculations, it can have a significant effect.

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