17.07.2015 Views

Defensive Database Programming - Red Gate Software

Defensive Database Programming - Red Gate Software

Defensive Database Programming - 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.

Chapter 5: Reusing T-SQL CodeOver the coming sections, we'll discuss other ways in which we can reuse T-SQL code,as dictated by the given circumstances. Overall, reusing code is a very importantcomponent of defensive programming, and I cannot emphasize strongly enough howmuch it can improve the robustness of our code.Wrapping SELECTs in ViewsIn some cases, it makes sense to wrap a frequently-used query in a view, as shown inListing 5-12.CREATE VIEW dbo.TotalSalesByStateASSELECT SUM(Amount) AS TotalSales, StateCodeFROM dbo.SalesGROUP BY StateCode ;Listing 5-12: Wrapping a query inside a view.You can SELECT from views in exactly the same way as you can SELECT from tables, soviews are very convenient and useful. However, views do not offer the ability to provideparameters to the SELECT statements that we are reusing. When this requirementarises, we reuse SELECT statements by wrapping them either in stored procedures or inuser-defined functions.As usual, we need to consider performance whenever we choose to use views. Typicallyviews do not cause any performance degradation at all. However, we need to use themin moderation: having to deal with too many layers of nested views may overwhelm theoptimizer and cause it to choose a suboptimal plan.Reusing Parameterized Queries: StoredProcedures versus Inline UDFsIf we want to reuse parameterized queries, it is usually preferable to wrap them in userdefinedfunctions. It is typically less convenient to reuse parameterized queries that arewrapped in stored procedures, as the following examples will demonstrate.141

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

Saved successfully!

Ooh no, something went wrong!