• afuchs 47083 (4/4/2013)


    Hi guys,

    I tried to create a new userdefined function for calculating the average of top 10 values on different columns of my table:

    Example:

    SELECT AVG(a02) FROM (SELECT TOP 10 a02 FROM table01 WHERE pkart3='A' AND pkid='Y' ORDER BY lfnr DESC) u

    This works fine. But I get an error on creating this function:

    CREATE FUNCTION dbo.rollavg (@data_in char(3))

    RETURNS int

    AS

    BEGIN

    DECLARE @data_out int

    SET @data_out = AVG(u.data) FROM (SELECT TOP 10 @data_in AS data FROM table01 WHERE pkart3='A' ORDER BY lfnr DESC) u

    RETURN @data_out

    END

    I thought to use this function: SELECT dbo.rollavg(a02) AS [ra02] FROM table01

    Can anyone help me?

    Thanks a lot!

    Yes - don't do it!!

    For the sake of a little code simplification, the cost of using a scalar udf simply isn't worth it. Scalar udf's prohibit parallelism in all or part of the execution plan and are executed for every row of the part of the plan where they are called.

    On the other hand, if you're seeking an average for a range of different values for pkart3 then there are tricks you could use, such as an iTVF or just a plain ol' CROSS APPLY.

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden