Log in  ::  Register  ::  Not logged in

## Inline Valued Function query...

 Author Message alik_therock SSC Journeyman Group: General Forum Members Points: 75 Visits: 33 Afternoon all,Looking for a bit of advice on something I am struggling to explain. I have 3 functions, 2 of which are examples provided by Adam Machanic in a useful post he did on Scalar Functions vs Inline Functions. The functions use AdventureWorks and are as follows:------------------------------------------------------FUNCTION 1 - Inline Function 1:CREATE FUNCTION [dbo].[GetMaxProductQty_Inline_Test1]( @ProductId INT)RETURNS TABLEAS RETURN ( SELECT MAX(sod.OrderQty) AS maxqty FROM Sales.SalesOrderDetail sod WHERE sod.ProductId = @ProductId )FUNCTION 2 - Inline Function 2:CREATE FUNCTION GetMaxProductQty_Inline_Test2( @ProductId INT)RETURNS @test TABLE (MaxQty INT)ASBEGIN DECLARE @MaxQty INT SELECT @MaxQty = (SELECT MAX(sod.OrderQty) AS maxqty FROM Sales.SalesOrderDetail sod WHERE sod.ProductId = @ProductId) INSERT INTO @test (MaxQty) VALUES (@MaxQty) RETURNENDFUNCTION 3 - Scalar Function:CREATE FUNCTION GetMaxProductQty_Scalar_Test1( @ProductId INT)RETURNS INTASBEGIN DECLARE @maxQty INT SELECT @maxQty = MAX(sod.OrderQty) FROM Sales.SalesOrderDetail sod WHERE sod.ProductId = @ProductId RETURN (@maxQty)END------------------------------------------------------I used this to give people an easy to understand example with the implications of a Scalar Functions vs Inline Function when they are both setup to return a similar results set. Inline Function 1 vs Scalar Function 1 highlighted what Adam described in his blog post in that the Inline Function was 288 times quicker and did 1200 (ish) Reads vs 365,000 (ish) Reads of the Scalar Function, and consumed vastly less CPU and in the process, allowed an optimised Execution Plan to be generated detailing exactly what was happening, rather than the Black Box Approach of the Scalar Function.However, I set about re-writing the Inline Function to try and utilise parameters to return as a Table, which spawned Inline Function 2...This function when used in exactly the same way as Inline Function 1, allowed SQL to generate a plan, but in reality still did a similar amount of Reads to the Scalar Function, only this time it was visible as to what was going on under the covers and what I deem to be the culprit which was a Nested Loop, which was cycling through the results in a similar way to the Scalar Function with a Row by Row Cursor like approach which was just as bad on performance, only more visible through the Execution Plan.What I am struggling to understand is why Inline Function 1 is so superior to Inline Function 2 when they both run Inline with the query and they both allow SQL to generate a useful Execution Plan of what is going on behind the scenes. The obvious answer is the Nested Loop, but I am looking for more detail than this if possible. The SQL used to execute both these queries is as follows:-------------------------------------------------------- Inline Function 1 --SELECT ProductId, ( SELECT MaxQty FROM dbo.GetMaxProductQty_Inline_Test1(ProductId) ) MaxQtyFROM Production.ProductORDER BY ProductId-- Inline Function 2 --SELECT ProductId, ( SELECT MaxQty FROM dbo.GetMaxProductQty_Inline_Test2(ProductId) ) MaxQtyFROM Production.ProductORDER BY ProductID------------------------------------------------------Any advice on this would be massively appreciated.Cheers Sean Lange SSC Guru Group: General Forum Members Points: 147734 Visits: 18566 Your "inline" function #2 is basically the same thing as a scalar function. It is multiple line function which means it behaves the same way. In fact, many time a multiline table function will perform even worse than a scalar function. In essence your function #2 is no longer an ITVF, it is now a MSTVF (multi statement table valued function).Check out this post which does a great job explaining the differences. Make sure you read the comments to because there is another great article linked to there.http://www.sqlservercentral.com/blogs/discussionofsqlserver/2012/02/15/comparing-inline-and-multistatement-table-valued-functions/ _______________________________________________________________Need help? Help us help you. Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.Need to split a string? Try Jeff Modens splitter.Cross Tabs and Pivots, Part 1 – Converting Rows to Columns Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs Understanding and Using APPLY (Part 1)Understanding and Using APPLY (Part 2) Jeff Moden SSC Guru Group: General Forum Members Points: 505092 Visits: 44240 Just so you know, Function2 is NOT an iTVF (Inline Table Valued Function). Rather, it's an mTFV (Multiline Table Valued Function) and those can be as bad or worse than a Scalar Function. I can't tell because you didn't list the final modified code for function 2 but if it still contains the table definition and the BEGIN/END, then it's still an mTVF and will still perform poorly as before. --Jeff ModenRBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.First step towards the paradigm shift of writing Set Based code: Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair Helpful Links:How to post code problemsHow to post performance problemsForum FAQs alik_therock SSC Journeyman Group: General Forum Members Points: 75 Visits: 33 Cheers guys.The final code does include a Begin/End as part of the Table Valued Function so will be the same as you describe.I will use this going forward, thanks once again. dwain.c SSC-Forever Group: General Forum Members Points: 43911 Visits: 6431 Jeff Moden (10/3/2013)Rather, it's an mTFV (Multiline Table Valued Function) and those can be as bad or worse than a Scalar Function. They can? Not that I'm a disbeliever of course. It's just that usually when you make a statement like that you've got something in your back pocket to prove it. My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!My thought question: Have you ever been told that your query runs too fast?My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables Jeff Moden SSC Guru Group: General Forum Members Points: 505092 Visits: 44240 dwain.c (10/3/2013)Jeff Moden (10/3/2013)Rather, it's an mTFV (Multiline Table Valued Function) and those can be as bad or worse than a Scalar Function. They can? Not that I'm a disbeliever of course. It's just that usually when you make a statement like that you've got something in your back pocket to prove it.I 've been busy and just didn't have the time to prove the point. Of course, you're correct. People shouldn't make claims of performance without proof in the code. With that in mind, here's code to create a test table, and mTVF, and an equivalent iTVF (equivalent in function)...`--===== Do these tests in a nice, safe place that everyone has. USE tempdb;--===== Create and populate a super simple test table. SELECT TOP 1000 SomeInt = IDENTITY(INT,1,1) INTO dbo.TestTable FROM master.sys.all_columns ac1 CROSS JOIN master.sys.all_columns ac2;GO--===== Create the mTVF to create a times table from 1 to 1000 for the @Multiplier CREATE FUNCTION dbo.mTVF (@Multiplier INT)RETURNS @Result TABLE (Multiplican INT, Multiplier INT, Product INT) WITH SCHEMABINDING AS BEGIN INSERT INTO @Result (Multiplican, Multiplier, Product) SELECT Multiplican = SomeInt ,Multiplier = @Multiplier ,Product = SomeInt * @Multiplier FROM dbo.TestTable ; RETURN ; END;GO--===== Create the iTVF to create a times table from 1 to 1000 for the @Multiplier CREATE FUNCTION dbo.iTVF (@Multiplier INT)RETURNS TABLE WITH SCHEMABINDING AS RETURN SELECT Multiplican = SomeInt ,Multiplier = @Multiplier ,Product = SomeInt * @Multiplier FROM dbo.TestTable ;GO`Here's the code I used to test the functions without SQL Profiler running. The output has been directed to variables to take display times out of the picture. Each run produces a million row vertical "Times Table" based on 1000 * 1000 and each code example is executed 3 times. I primed the pump by running this code once and then turned on SQL Profiler to measure the performance.`--===== Test the mTVF for perfomance in it's own batchDECLARE @Bitbucket1 INT ,@Bitbucket2 INT ,@Bitbucket3 INT; SELECT @Bitbucket1 = mult.Multiplican ,@Bitbucket2 = mult.Multiplier ,@Bitbucket3 = mult.Product FROM dbo.TestTable tt CROSS APPLY dbo.mTVF(tt.SomeInt) mult;GO 3--===== Test the iTVF for perfomance in it's own batchDECLARE @Bitbucket1 INT ,@Bitbucket2 INT ,@Bitbucket3 INT; SELECT @Bitbucket1 = mult.Multiplican ,@Bitbucket2 = mult.Multiplier ,@Bitbucket3 = mult.Product FROM dbo.TestTable tt CROSS APPLY dbo.iTVF(tt.SomeInt) mult;GO 3`Here are the results from profiler. Like I said, mTVF's can be as bad as SF's when it comes to performance. From here, it looks like the iTVF runs an average of 11.8 times faster than the mTVF and uses a whole lot less resources. --Jeff ModenRBAR is pronounced ree-bar and is a Modenism for Row-By-Agonizing-Row.First step towards the paradigm shift of writing Set Based code: Stop thinking about what you want to do to a row... think, instead, of what you want to do to a column.If you think its expensive to hire a professional to do the job, wait until you hire an amateur. -- Red Adair Helpful Links:How to post code problemsHow to post performance problemsForum FAQs Attachments mTVF vs iTVF Performance.PNG (64 views, 14.00 KB) dwain.c SSC-Forever Group: General Forum Members Points: 43911 Visits: 6431 The magnitude of the difference in your profiler trace does suggest that mTVFs could be in the same range as SFs.Thanks for taking the time on it. My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!My thought question: Have you ever been told that your query runs too fast?My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables

## Permissions

 You can't post new topics. You can't post topic replies. You can't post new polls. You can't post replies to polls. You can't edit your own topics. You can't delete your own topics. You can't edit other topics. You can't delete other topics. You can't edit your own posts. You can't edit other posts. You can't delete your own posts. You can't delete other posts. You can't post events. You can't edit your own events. You can't edit other events. You can't delete your own events. You can't delete other events. You can't send private messages. You can't send emails. You can read topics. You can't vote in polls. You can't upload attachments. You can download attachments. You can't post HTML code. You can't edit HTML code. You can't post IFCode. You can't post JavaScript. You can post emoticons. You can't post or upload images.

##### Select a forum
 SQL Server 2017      SQL Server 2017 - Administration      SQL Server 2017 - Development SQL Server 2016      SQL Server 2016 - Administration      SQL Server 2016 - Development and T-SQL SQL Server 2014      Administration - SQL Server 2014      Development - SQL Server 2014 SQL Server 2012      SQL 2012 - General      SQL Server 2012 - T-SQL SQL Server vNext      SQL Server 15 - Administration      SQL Server 15 - Development SQL Server 2008      SQL Server 2008 - General      T-SQL (SS2K8)      June 2007 CTP      Working with Oracle      July CTP      SQL Server Newbies      Security (SS2K8)      SQL Server 2008 High Availability      SQL Server 2008 Administration      Data Corruption (SS2K8 / SS2K8 R2)      SQL Server 2008 Performance Tuning Cloud Computing      SQL Azure - Development      SQL Azure - Administration      Amazon AWS and other cloud vendors      General Cloud Computing Questions      CosmosDB      Azure Data Lake      Azure Machine Learning Reporting Services      Reporting Services      Reporting Services 2005 Administration      Reporting Services 2005 Development      Reporting Services 2008/R2 Administration      Reporting Services 2008 Development      SSRS 2012      SSRS 2014      SSRS 2016 Programming      Connecting      General      SMO/RMO/DMO      XML      Service Broker      Powershell      Testing      TFS/Data Dude/DBPro      SSDT      Continuous Integration, Deployment, and Delivery      R Services and R Language Data Warehousing      Integration Services      Strategies and Ideas      Analysis Services      Data Transformation Services (DTS)      Performance Point      Data Mining      PowerPivot      R language      Machine Learning Database Design      Disaster Recovery      Design Ideas and Questions      Relational Theory      Hardware      Virtualization      Security and Auditing SQLServerCentral.com      Anything that is NOT about SQL!      Contests!      Editorials      SQLServerCentral.com Announcements      SQLServerCentral.com Website Issues      Suggestions      Tag Issues with Content      Podcast Feedback      SQLServerCentral.com Test Forum      Articles Requested SQL Server 2005      Administering      Backups      Business Intelligence      CLR Integration and Programming.      Data Corruption      Development      Working with Oracle      SQL Server 2005 Compact Edition      SQL Server 2005 General Discussion      SQL Server 2005 Security      SQL Server 2005 Strategies      SS2K5 Replication      SQL Server Express      SQL Server 2005 Performance Tuning      SQL Server 2005 Integration Services      T-SQL (SS2K5)      SQL Server Newbies SQL Server 7,2000      Administration      Backups      Data Corruption      General      Globalization      In The Enterprise      Working with Oracle      Security      Strategies      SQL Server Newbies      Service Packs      SQL Server CE      Performance Tuning      Replication      Sarbanes-Oxley      T-SQL      SQL Server Agent SQL Server and other platforms      MySQL      Oracle      PostgreSQL      DB2      SQL Server and Sharepoint Older Versions of SQL (v6.5, v6.0, v4.2)      Older Versions of SQL (v6.5, v6.0, v4.2) Career      Certification      Employers and Employees      Events      Job Postings      Resumes and Job Hunters      Presentations and Speaking      Retired Members Testing Center      SQL Server Security Skills      Question of the Day (QOD) Microsoft Access      Microsoft Access Products and Books      Third Party Products         SQLCentric         Extreme Technologies.         Innovartis         Embarcadero         SQL Sentry         Sonasoft         Golden Gate Software         Idera         Lumigent         Red Gate Software         ApexSQL         Quest Software         CA      Discussions about Books         Discuss Programming Books          Discuss XML Books          Discuss T-SQL Books          Discuss Data Warehousing Books          Discuss DTS Books          Discuss SQL Server 2000 Books         Discuss SQL Server 7.0 Books Notification Services      Administration Article Discussions Future Versions      SQL 12

## Search

 Copyright © 2002-2018 Redgate. All Rights Reserved. Privacy Policy. Terms of Use. Report Abuse.