Introduction
Anyone can learn a little about creating and/or accessing a database nowadays. Just take a minute to browse your local bookstore and you will find a plethora of books on the subject. And while I feel that it is wonderful that all of this knowledge is so easily attainable, I also find it frustrating. It seems that many times what is being taught is often the "fast and easy" way to do something with no mention of the repercussions of building actual applications in such a manner. What I commonly find missing from these textbooks is any consideration of the following core aspects of professional database development and deployment:
SECURITYPERFORMANCE MAINTAINABILITY
Database access is a subject that deserves consideration as part of the overall database architecture, and not just a quick demonstration of the simplest and most easily described methods. Applications designed without a data access forethought can be the most difficult to secure, support, maintain and enhance. Designing your application so that Stored Procedures are the only database objects that are accessed is generally the best practice. In fact, Stored Procedures should be used in SQL Server for Data Manipulation Language (DML) . This premise is written with the following assumptions in mind:
Assumptions...
The simple fact is, using Stored Procedures in conjunction with a well defined development standard to consolidate your Insert, Update, Delete and Select statements will vastly improve the security, performance and maintainability of your application at a minimal/negligable cost.
Security
*Some type of Business Rules and Transactions may not be appropriately placed in Stored Procedures depending upon the application design and the decision of the layer in which to place this type of logic. In many cases, some Business Logic arguably belongs in it's own object layer(s), and transactions may be handled by entities other than just SQL Server (like MTS). However, in many basic development environments, Business Logic and Transactions are best segregated in the Stored Procedures. These items do need to be considered early in development, and organized in a centralized, predictable and manageable fashion.
Performance
In my experience, there are basically five ways in which data in a SQL Server is manipulated, let's briefly look at each :
1. Data Access Methods (ADO, RDO, DAO, etc)2. Dynamic/Embedded SQL Statements in Code such as VB/ASP 3. Updateable Views4. Dynamic-SQL Stored Procedures (non-compiled SQL) 5. Static Stored Procedures
Precompiled Code One reason why stored procedures improve an application's performance is that the SQL code is precompiled. When a stored procedure is saved in the database, SQL Server parses the syntax for accuracy and saves the procedure's text in the syscomments table. Upon the initial execution, the query processor checks to see that the referenced objects exist. If they do, SQL Server compiles an execution plan and stores it in memory in an area called the procedure cache. As a result, SQL Server doesn't have to reconstruct the same query plan over and over again, and already knows the indexes it will use and the strategy it will take to return query resultset. Multi-step Processes Another performance gain from stored procedures is that you can perform multi-step processes requiring conditional logic, entirely within a stored procedure. You simply call the procedure and pass it all the parameters required for the process. The procedure can then use Transact SQL (T-SQL) conditional statements (CASE statements are designed for this purpose) to make decisions rather than have the client application submit a query to the server, retrieve the result set, make the decision, and finally submit another query to perform the action. These additional round trips to the server consume network bandwidth, not to mention processing time. Efficiently Written Code When combined with the proper development process and personnel, requiring all DML be contained within stored procedures can help to assure that all SQL will be either written or reviewed by a knowledgeable SQL person who understands the underlying index structures and the concept of optimization. Obviously, poorly structured SQL can cause performance issues as locks escalate and resources are consumed. One good example of this is that select statements on heavily used tables that do not require up to the second information can be given the "with (NOLOCK)" hint to allow a dirty read. If all requests for information go through the same interface (that table's "select" stored procedure), locked records and timeout issues in the application can be avoided. Reduced Network Traffic & CPU Processor Time Calling a stored procedure only requires sending the stored procedure and parameters across the network instead of an entire SQL String. Plus, the stored procedure can decide what type of update needs to take place instead of successive SQL statements traveling back and forth as conditional instructions are followed from another location (IIS/ASP, COM or within a client). One additional note: While it may take more code, it is worthwhile to create parameters for your stored procedure calls explicitly in your code instead of using the .Refresh ADO method. Doing so eliminates back and forth trips to the server to provide a list of parameters and will speed things up even more.
Efficiently Written Code When combined with the proper development process and personnel, requiring all DML be contained within stored procedures can help to assure that all SQL will be either written or reviewed by a knowledgeable SQL person who understands the underlying index structures and the concept of optimization. Obviously, poorly structured SQL can cause performance issues as locks escalate and resources are consumed. One good example of this is that select statements on heavily used tables that do not require up to the second information can be given the "with (NOLOCK)" hint to allow a dirty read. If all requests for information go through the same interface (that table's "select" stored procedure), locked records and timeout issues in the application can be avoided.
One additional note: While it may take more code, it is worthwhile to create parameters for your stored procedure calls explicitly in your code instead of using the .Refresh ADO method. Doing so eliminates back and forth trips to the server to provide a list of parameters and will speed things up even more.
Maintainability
The last, and probably most significant reason for using Stored Procedures for DML and making data access it's own "layer" is that the level of complexity related to database alterations is greatly decreased. This strategy has many benefits:
Example DML Naming Conventions
Option 1 ins_company ins_order ins_order_detail upd_company upd_order upd_order_detail del_company del_order del_order_detail
Option 2 pi_company pi_order pi_order_detail pu_company pu_order pu_order_detail pd_company pd_order pd_order_detail
By requiring all inserts, updates, deletes and selects occur through stored procedures named in such a way, a database change becomes fairly straightforward. Otherwise, one would need to go through the familiar task of changing views, stored procedures, asp code, vb code, include files, Access databases, Crystal Reports, etc...!
Summary
I am aware that there are many ways to access data, but I am of the general opinion that DML itself does not belong scattered all over an application. It is too difficult to maintain, secure and nearly impossible to optimize. Plan ahead when doing your development, otherwise most developers will unthinkingly follow the shortest development path - sacrificing stability, efficiency and long term development efforts.
Tools
Related Articles
Performance Tuning for SQL Server Developers ADO Performance Best Practices Implementing SQL Server in an OLTP Environment Performance Tuning Tips for Creating VB Applications using SQL Server Microsoft MSDN - Coding Techniques and Programming Practices Microsoft MSDN - Designing Efficient Applications for Microsoft SQL Server Microsoft MSDN - Top Ten Tips: Accessing SQL Through ADO and ASP Using Stored Procedures instead of Dynamic SQL Using Stored Procedures with ASP, ADO and SQL Server
Books
SQL Server 2000 Resource Kit Professional ASP Data Access Beginning ASP Databases Professional SQL Server 7
To read the rest of this article, and access thousands of other articles, we ask you to register on the site and subscribe to our newsletters.
We ask you to register on the site and subscribe to our newsletters. Subscribing to our newsletters gets you:
We ask that you give the newsletter a try for a week. Over 200,000 SQL Server Professionals a day find it entertaining and useful. If not, you are welcome to unsubscribe at anytime.
Steve Jones Editor, SQLServerCentral.com