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.

Client problems when reading data<br />

325<br />

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

Use of SELECT * can cause duplicate column names to be returned in the result set, as<br />

demonstrated in Listing 11-6. This will definitely cause client applications to throw an<br />

exception when attempting to read columns by name. Always explicitly name the columns<br />

to be returned and alias columns with the same names. If there are multiple columns<br />

with the same name, then it might be a good idea to prefix the column names with a table<br />

identifier, such as t1_name. However, this will change our output column names.<br />

SELECT TOP 10<br />

*<br />

FROM master..spt_values t1<br />

CROSS JOIN master..spt_values t2<br />

- – same result set but with explicitly named columns<br />

SELECT TOP 10<br />

t1.name , t1.number , t1.type ,<br />

t1.high , t1.low , t1.status ,<br />

t2.name , t2.number , t2.type ,<br />

t2.high , t2.low , t2.status<br />

FROM master..spt_values t1<br />

CROSS JOIN master..spt_values t2<br />

Listing 11-6: Duplicate names due to use of SELECT *.<br />

View refreshing problem<br />

This is one of the trickier problems with SELECT *. If we use it in a view, and a column is<br />

added to an underlying table, then this change isn't reflected in the view. We have to call a<br />

stored procedure called sp_refreshview to refresh the schema returned by the view, so<br />

our changes to the tables are seen. Listing 11-7 demonstrates this problem.

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

Saved successfully!

Ooh no, something went wrong!