Possible Duplicate:
What are the pros and cons to keeping SQL in Stored Procs versus Code
我在听Hanselminutes podcast "Rise of The Micro ORM,"其中一位嘉宾(Sam Saffron 和 Rob Conery)概述了 DBA 坚持使用存储过程的经典原因:
- 它们是预编译的,这给了它们执行速度的优势
- 它们隐藏了底层数据库方案,允许分离接口(interface)和实现以防止脆弱性。
然后一位客人说这些不是很好的论据,并建议 DBA 坚持使用存储过程的真正原因是因为他们只是想保护自己免受中间层开发人员的无知。
我发现这种说法有点极端。当然,我同意第 2 个论点有缺陷,但我认为众所周知,向数据库发送任意(未编译的)SQL 会影响性能。有没有我遗漏的东西可以解释为什么参数 #1 不是真的?
我自己的回答,只是一个猜测,是性能受到影响 - 但这并不重要。这可能类似于试图优化他编写的每个循环的开发人员,即使只有 1% 的编写循环从调整中受益。我是否正确地捕获了想法?
“但我认为众所周知,向数据库发送任意(未编译的)SQL 会影响性能。”
自 SQL 6.5 以来,您在存储过程和其他有关预编译的 sql 语句之间所做的区分不存在。
Stored Procedures and Execution Plans
In SQL Server version 6.5 and earlier,
stored procedures were a way to
partially precompile an execution
plan. At the time the stored procedure
was created, a partially compiled
execution plan was stored in a system
table. Executing a stored procedure
was more efficient than executing an
SQL statement because SQL Server did
not have to compile an execution plan
completely, it only had to finish
optimizing the stored plan for the
procedure. Also, the fully compiled
execution plan for the stored
procedure was retained in the SQL
Server procedure cache, meaning that
subsequent executions of the stored
procedure could use the precompiled
execution plan.
SQL Server 2000 and SQL Server version
7.0 incorporate a number of changes to statement processing that extend many
of the performance benefits of stored
procedures to all SQL statements. SQL
Server 2000 and SQL Server 7.0 do not
save a partially compiled plan for
stored procedures when they are
created. A stored procedure is
compiled at execution time, like any
other Transact-SQL statement. SQL
Server 2000 and SQL Server 7.0 retain
execution plans for all SQL statements
in the procedure cache, not just
stored procedure execution plans. The
database engine uses an efficient
algorithm for comparing new
Transact-SQL statements with the
Transact-SQL statements of existing
execution plans. If the database
engine determines that a new
Transact-SQL statement matches the
Transact-SQL statement of an existing
execution plan, it reuses the plan.
This reduces the relative performance
benefit of precompiling stored
procedures by extending execution plan
reuse to all SQL statements.
http://msdn.microsoft.com/en-us/library/aa174792%28v=sql.80%29.aspx