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

Solution 1:

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

Solution 2:

Because every time you pass a query string to SQL Server the code has to be compiled etc, stored procedures are already compiled and ready to run on the server.

Also you are sending less data over the network although this is generally a minimal impact anyway.

EDIT: As a side note stored procedures have other benefits.

1) Security - Since the actual query is stored on the server you are not transmitting this over the network which means anyone intercepting your network traffic does not gain any insight into your table structure. Also a well designed SP will prevent injection attacks.

2) Code seperation, you keep your database code in your database and your application code in your application, there is very little crossover and I find this makes bug fixing a lot nicer.

3) Maintainability and Code Reuse, you can reuse a procedure many times without having to copy paste the query, also if you wish to update the query you just have to update it in one place.

4) Decreased network traffic. As mentioned above this may not be an issue for most people but with a large application you can significantly reduce the ammount of data being transferred via your network by switching to using stored procedures.