Solved

When is Multi-Valued UDF faster than inline UDF?

Posted on 2012-03-13
8
303 Views
Last Modified: 2012-03-20
Hi,

I have rewritten an UDF from inline to multi-valued UDF and was able to reduce the query time from ~20seconds down to ~2seconds.  All the literature indicates that inline are generally faster than multi valued UDF's.  

The original inline query looked something like the following:

create function udf_inline
(
   @p1 int,
   @p2 datetime
)
returns table
as
return

select
    *
from
      (
            select
                         *
            from
                  (
                        select
                              *
                        from
                              tableA
                        where
                              col1 = @p1
                              and col2 = @p2
                  )
      )
            

I have rewritten the query to use multi lined UDF


CREATE FUNCTION dbo.MV_UDF
(
   @p1 INT,
   @p2 DATETIME
)


RETURNS @myTable TABLE
(
   colA varchar(50),
   colB varchar(50),
   etc...
)
AS
BEGIN


insert into @myTable
select
    *
from
      (
            select
                         *
            from
                  (
                        select
                              *
                        from
                              tableA
                        where
                              col1 = @p1
                              and col2 = @p2
                  )
      )
RETURN


Why the multi-valued UDF runs faster I do not know.  Anyone can provide some insight?

thanks
0
Comment
Question by:yechan
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
8 Comments
 
LVL 25

Expert Comment

by:jogos
ID: 37714562
Maintenance plan will learn you more about the different usage.
0
 
LVL 40

Expert Comment

by:lcohan
ID: 37716438
Actually your "inline" udf_inline function is NOT a inline but still a table function if you look at its definition (below) and yours is fater as you work with explicit @table in return and most likely better optimized. but in my opinion you can still get rid of one unnecessary SELECT * in your function code.


create function udf_inline
(
   @p1 int,
   @p2 datetime
)
returns table
as
0
 
LVL 40

Expert Comment

by:lcohan
ID: 37716467
Also it may faster because the data was cached from running prior "inline" code so it just look faster but it may be not for the first time you run it with SQL cold cache.
0
NEW Veeam Agent for Microsoft Windows

Backup and recover physical and cloud-based servers and workstations, as well as endpoint devices that belong to remote users. Avoid downtime and data loss quickly and easily for Windows-based physical or public cloud-based workloads!

 
LVL 40

Expert Comment

by:lcohan
ID: 37716521
And BTW....why not just a regular SQL stored proc if all you need a the record set returned byt the SQL code? I would use a table UDF if I need to join that record set but otherwise I would use from all aspects including performance just a regular SPROC like:

CREATE PROCEDURE dbo.My_SPROC
(
   @p1 INT,
   @p2 DATETIME
)
AS
SET NOCOUNT ON;

      select * from tableA
            where col1 = @p1 and col2 = @p2
       
RETURN
GO
0
 
LVL 1

Author Comment

by:yechan
ID: 37716793
Hi lcohan

Not sure why you would say that my inline function is not an inline function but is instead an Multi-Statement Table-Valued function.

Would love to convert it to a stored procedure but that function is being dynamically called from a web page but at this point, not sure if it is worth the trouble doing this.  At least not at the moent.
0
 
LVL 40

Accepted Solution

by:
lcohan earned 275 total points
ID: 37716885
What I was trying to say is that the original function would still return a table like record set and if you execute that first then the second having almost the same code you may be misled by the execution time agreed? SQL will cache code and data therefor running the same SQL code inside first "inline" function udf_inline will take longer than running the identical code immediately after that from your new dbo.MV_UDF table function.
To be certain please run the commands below in a test environment and DO <<NOT>> run it in a production SQL box because it will fully flush data and code SQL cache.
Run them before each inline or table udf call for a cold SQL cache.

dbcc dropcleanbuffers;
dbcc freeproccache;

you could also use

set statistics time on;
set statistics io on;

to see the actual exec/compile times and IO for both of your functions.
0
 
LVL 75

Assisted Solution

by:Anthony Perkins
Anthony Perkins earned 50 total points
ID: 37717652
Here is the definition from SQL Server's BOL for an Inline UDF

Inline user-defined functions follow these rules:

The RETURNS clause contains only the keyword table. You do not have to define the format of a return variable, because it is set by the format of the result set of the SELECT statement in the RETURN clause.
There is no function_body delimited by BEGIN and END.
The RETURN clause contains a single SELECT statement in parentheses. The result set of the SELECT statement forms the table returned by the function. The SELECT statement used in an inline function is subject to the same restrictions as SELECT statements used in views.
The table-valued function accepts only constants or @local_variable argument

So I would say yes, your first function is an Inline User-Defined Function.

But the point about caching is well made.  An Inline function should always out-perform a Multi-Statement function.  In other words, it may be just your perception.
0
 
LVL 1

Author Comment

by:yechan
ID: 37741896
Sorry for getting back so late.  Turns out that the web application wraps sql statements around sp_executesql whereas in SSMS I do not use sp_executesql.  This defn. changed things and probably explains the behavior.  Thank you for all the feedback.
0

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Sql query with where clause 2 54
get_systemdrive info from tsql? 1 26
Checking for column changes SQL 2014 4 40
T-SQL: How to append a column for serialized JSON data? 2 49
If you have heard of RFC822 date formats, they can be quite a challenge in SQL Server. RFC822 is an Internet standard format for email message headers, including all dates within those headers. The RFC822 protocols are available in detail at:   ht…
Occasionally there is a need to clean table columns, especially if you have inherited legacy data. There are obviously many ways to accomplish that, including elaborate UPDATE queries with anywhere from one to numerous REPLACE functions (even within…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…
In an interesting question (https://www.experts-exchange.com/questions/29008360/) here at Experts Exchange, a member asked how to split a single image into multiple images. The primary usage for this is to place many photographs on a flatbed scanner…

737 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question