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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5: Reusing T-SQL CodeStateCode TotalSales--------- ---------------------------------------CA 140010000.00OR 28002000.00(2 row(s) affected)StateCode TotalSales--------- ---------------------------------------CA 140010000.00(1 row(s) affected)Listing 5-19: Testing the inline UDFs.It is often easier to reuse code when it is wrapped in inline UDFs than when it iswrapped in stored procedures. I should emphasize that I refer only to inline UDFs,not to all three varieties of UDF. Whenever we are deciding whether to use storedprocedures or UDFs, we also need to consider the following:• INSERT EXEC requires you to create a table variable or temporary table before doingthe call; stored procedures can have multiple and/or varying result sets, dependingon code path, causing all kinds of problems with INSERT EXEC• some functionality, such as data modifications and TRY…CATCH blocks, is notallowed in UDFs• the inline UDF, like a view, is expanded in the execution plan, giving the optimizerthe choice to take shortcuts, or even remove joined tables if their columns arenot used.Let's discuss performance considerations and see why it might not be a good idea to usescalar UDFs.146

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

Saved successfully!

Ooh no, something went wrong!