7 Designing .NET Applications for Performance Optimization : Simplifying Automatically-generated SQL Queries

Simplifying Automatically-generated SQL Queries
The guidelines in this section help you to optimize system performance by editing or eliminating complex automatically-generated SQL queries.
Reviewing SQL Queries Created by Visual Studio Wizards
Tools such as the Add Table Wizard and Add View Wizard are convenient to use. You can quickly select the tables, columns, rows, and fields that you want to include in your query. However, this can result in a complex query, as shown in the following figure.
Always review the generated SQL to make sure that the syntax is efficient and that the query contains only essential components.
Review SQL dialog for the Add View Wizard
Avoiding the CommandBuilder Object
It is tempting to use a CommandBuilder object because it generates SQL statements and can save the developer time when coding a new application that uses DataSets. However, this shortcut can have a negative effect on performance. Because of concurrency restrictions, the Command Builder can generate highly inefficient SQL statements. For example, suppose you have a table called emp, an 8-column table with simple employee records. A CommandBuilder would generate the following Update statement, which checks all values for concurrency restrictions:
CommandText: "UPDATE emp SET empno = ?, ename = ?, job = ?, mgr = ?, hiredate = ?, sal = ?, comm = ?, dept = ? WHERE ( (empno = ?) AND (ename = ?) AND (job = ?) AND ((mgr IS NULL AND ? IS NULL) OR (mgr = ?)) AND (hiredate = ?) AND (sal = ?) AND ((comm IS NULL AND ? IS NULL) OR (comm = ?)) AND (dept = ?) )"
The end user can often write much more efficient Update and Delete statements than those that the CommandBuilder generates. For example, a programmer who knows the underlying database schema and that the empno column of the emp table is the primary key for the table, can code the same Update statement as follows:
UPDATE emp SET empno = ?, ename = ?, job = ?, mgr = ?, hiredate = ?, sal = ?, comm = ?, dept = ? WHERE empno = ?
This statement runs much more efficiently on the database server than the statement that is generated by the CommandBuilder, but loses the additional concurrency control.
Another drawback is also implicit in the design of the CommandBuilder object. The CommandBuilder must generate statements at runtime. Each time a DataAdapter.Update method is called, the CommandBuilder must analyze the contents of the result set and generate Update, Insert, and Delete statements for the DataAdapter. When the programmer explicitly specifies the Update, Insert, and Delete statements for the DataAdapter, this extra processing time is avoided.