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.

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

same as a table scan) instead of a possible index seek, thus possibly increasing I/O reads<br />

and execution time by an order of magnitude.<br />

The solution to this problem is to rewrite the query so that the function is used, not on<br />

the column, but on the value to which we're comparing the column values. To see this<br />

in action, let's set up a test table, an index and 1 million rows of test data, as shown in<br />

Listing 11-3.<br />

CREATE TABLE TestTable<br />

(<br />

ID INT IDENTITY(1, 1)<br />

PRIMARY KEY, – – also creates a Clustered Index<br />

MyDate DATETIME<br />

)<br />

GO<br />

CREATE NONCLUSTERED INDEX NCI_TestTable_MyDate<br />

ON TestTable(MyDate)<br />

- – insert some test data<br />

INSERT INTO TestTable(MyDate)<br />

SELECT TOP 1000000<br />

– – insert million rows going back in time from now<br />

– – at one minute intervals.<br />

DATEADD(n, – ROW_NUMBER()<br />

OVER ( ORDER BY t1.number ),<br />

GETDATE())<br />

FROM master..spt_values t1<br />

CROSS JOIN master..spt_values t2<br />

GO<br />

Listing 11-3: A test table, with index and some test data.<br />

322

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

Saved successfully!

Ooh no, something went wrong!