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 CodeSELECT SUM(dbo.GetShippingCost(WeightInPounds))AS TotalShippingCostFROM dbo.Packages ;PRINT 'Using an inline UDF' ;SELECT SUM(s.ShippingCost) AS TotalShippingCostFROM dbo.Packages AS p CROSS APPLYdbo.GetShippingCost_Inline(p.WeightInPounds) AS s;PRINT 'Not using any functions at all' ;SELECT SUM(CASE WHEN p.WeightInPounds < 5 THEN 1.00ELSE 2.00END) AS TotalShippingCostFROM dbo.Packages AS p ;SET STATISTICS TIME OFF ;Listing 5-23: A simple benchmark to compare the performance of the scalar and inlineUDFs vs. the performance of the copy-and-paste approach.Although both functions implement exactly the same algorithm, the performance isdramatically different. When we run this benchmark on SQL Server 2005 or 2008, thequery that uses our scalar UDF runs dramatically slower. Also, in this particular case, thequery which uses the inline UDF performs very well, although not as fast as the querythat does not use any UDFs at all, as shown in Listing 5-24. Of course, when you runthese benchmarks on your system, you may get different results.Using a scalar UDF……SQL Server Execution Times:CPU time = 1531 ms, elapsed time = 1552 ms.Using an inline UDF150

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

Saved successfully!

Ooh no, something went wrong!