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.

331<br />

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

short, let this anti-pattern serve as a reminder never to put business logic inside your<br />

stored procedures, unless you really, really know what you're doing.<br />

The "one subquery per condition" anti-pattern<br />

This is a very common anti-pattern in reporting queries where the requirement is to<br />

perform aggregations <strong>based</strong> on certain conditions, for example: "return the count and<br />

sum for each product in the table, <strong>based</strong> on condition1, condition2, and so on."<br />

The trap that many developers fall into is assuming that the only way to apply the<br />

conditions is in the WHERE clause. Since you can only have one WHERE clause per <strong>SQL</strong><br />

statement, the solution many developers reach is to have a subquery for each separate<br />

condition. I can't really blame them, as it seems a logical conclusion to reach.<br />

To demonstrate, let's first create and populate a test table, as shown in Listing 11-9.<br />

IF OBJECT_ID('#TestTable') IS NOT NULL<br />

DROP TABLE #TestTable<br />

/*<br />

Create a simple test table with names we'll group on and some random data<br />

*/<br />

SELECT TOP 100000<br />

t1.name ,<br />

– – get random numbers<br />

ABS(CONVERT(INT, CONVERT(VARBINARY(50),<br />

NEWID())) / 100000000) AS number ,<br />

t1.type<br />

INTO #TestTable<br />

FROM master..spt_values t1<br />

CROSS JOIN master..spt_values t2<br />

GO<br />

Listing 11-9: Creating and populating our test table.

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

Saved successfully!

Ooh no, something went wrong!