30.06.2013 Views

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SQL Server Team-based Development - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

319<br />

Chapter 11: <strong>SQL</strong> Refactoring<br />

Before we even consider refactoring your <strong>SQL</strong> code, it's worth performing a sanity<br />

check on the existing indexing strategy. Maybe all we need to do is add or remove a<br />

few indexes and not really touch any code. There are two DMOs, sys.dm_db_index_<br />

operational_stats and sys.dm_db_index_usage_stats that can be used to<br />

investigate usage of current indexes, and a set of four sys.dm_db_missing_index_*<br />

DMOs that will report on indexes that that the query optimizer might find useful, but are<br />

missing. Microsoft Books Online is a good reference source for the DMOs, as is the book,<br />

Performance Tuning with <strong>SQL</strong> <strong>Server</strong> Dynamic Management Views by Louis Davidson and<br />

Tim Ford (http://tinyurl.com/3x5cc9c).<br />

At the start of any refactoring effort, one of the things I do is run the script shown in<br />

Listing 11-2. It queries a system view and INFORMATION_SCHEMA view, looking for some<br />

of the most common "signs of trouble," including objects with long definitions (over 5,000<br />

chars), cursors, functions on column names and use of SELECT *. We'll examine each of<br />

these "anti-patterns" in more detail a little later.<br />

WITH cteObjectText<br />

AS (<br />

– – get text of objects that have it<br />

– – in the list we're checking the text of<br />

– – CHECK_CONSTRAINT, DEFAULT_CONSTRAINT,<br />

– – <strong>SQL</strong>_SCALAR_FUNCTION, <strong>SQL</strong>_STORED_PROCEDURE,<br />

– – <strong>SQL</strong>_TABLE_VALUED_FUNCTION, <strong>SQL</strong>_TRIGGER, VIEW<br />

SELECT OBJECT_DEFINITION(object_id) object_text ,<br />

name ,<br />

object_id<br />

FROM sys.objects<br />

WHERE type IN ( 'C', 'D', 'FN', 'P', 'TF', 'TR',<br />

'V' )<br />

),<br />

cteColumnNames<br />

AS (<br />

– – get all distinct column names in the database<br />

SELECT DISTINCT<br />

'(' + COLUMN_NAME AS LeftParen ,<br />

COLUMN_NAME + ')' AS RightParen<br />

FROM INFORMATION_SCHEMA.COLUMNS

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!