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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

*<br />

Populate the table with 100000 rows with random GUID<br />

values. We'll overwrite them with the update anyway<br />

*/<br />

INSERT INTO #LoopingIsBad<br />

( OurData<br />

)<br />

SELECT TOP 100000<br />

NEWID()<br />

FROM master..spt_values t1<br />

CROSS JOIN master..spt_values t2<br />

GO<br />

Listing 11-12: Creating and populating the #LoopingIsBad temporary test table.<br />

335<br />

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

Let's say we need to update the OurData column, <strong>based</strong> on the following complex<br />

UPDATE rules.<br />

1. If OurData value contains the substring ABCD, replace it with ABCD only.<br />

2. If OurData value starts with E or F, replace it with E and F, respectively, plus<br />

today's date.<br />

3. If OurData value ends with 1, 2, 3, or 4 replace the value with 1, 2, 3, or 4 accordingly<br />

(so, for example, abc1 would become 1, bfd2 would become 2, and so on).<br />

4. If OurData value ends with 5 or 6 replace it with NULL.<br />

5. For any other values, don't change the value.<br />

Listing 11-13 shows the cursor-<strong>based</strong> approach, which is the first (and only) one considered<br />

by many developers.

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

Saved successfully!

Ooh no, something went wrong!