Code Review :: SQL Server 2012
You are asked to review the code in a system that suffers from both code maintainability
problems and performance problems. You come up with the following findings and need to
determine what to recommend to the customer:
- You find many queries that use a number of nesting levels of derived tables, making
it very hard to follow the logic. You also find a lot of queries that join multiple derived
tables that are based on the same query, and you find that some queries are repeated
in a number of places in the code. What can you recommend to the customer to reduce
the complexity and improve maintainability?
- During your review, you identify a number of cases where cursors are used to access
the instances of a certain entity (like customer, employee, shipper) one at a time; next
the code invokes a query per each of those instances, storing the result in a temporary
table; then the code just returns all the rows from the temporary tables. The customer
has both code maintainability and performance problems with the existing code. What
can you recommend?
- You identify performance issues with joins. You realize that there are no indexes created
explicitly in the system; there are only the ones created by default through primary
key and unique constraints. What can you recommend?
Answers- To address the nesting complexity of derived tables, in addition to the duplication of
derived table code, you can use CTEs. CTEs don't nest; instead, they are more modular.
Also, you can define a CTE once and refer to it multiple times in the outer query. As
for queries that are repeated in different places in your code for reusability you can
use views and inline table-valued functions. Use the former if you don't need to pass
parameters and the latter if you do.
- The customer should evaluate the use of the APPLY operator instead of the cursor plus
the query per row. The APPLY operator involves less code and therefore improves the
maintainability, and it does not incur the performance hit that cursors usually do.
- The customer should examine foreign key relationships and evaluate creating indexes
on the foreign key columns.