Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UDF inside an SP performance issue on ms sql

I have the following SP

PROCEDURE [dbo].[order_s]
(
    @user Uniqueidentifier
)
AS
BEGIN
SET NOCOUNT ON;
SELECT 
      id,
      name,
      [begin],
      [end]
FROM 
      orders 
WHERE
    @user = dbo.hasAccess(@user,id,'select')
END

This SP calls a this UDF

    FUNCTION [dbo].[hasAccess] 
    (
        @user uniqueidentifier,
        @orderId bigint,
        @AccessType nchar(10)
    )
    RETURNS uniqueidentifier
    AS
    BEGIN
        DECLARE @Result uniqueidentifier

        SELECT 
            Top 1 @Result = [user] 
        FROM 
            access 
        WHERE 
            orderId = @orderId AND
            [user] = @user AND
            role >= CASE    
                        WHEN @AccessType = 'select' then 1
                        WHEN @AccessType = 'insert' then 5
                        WHEN @AccessType = 'update' then 7
                        WHEN @AccessType = 'delete' then 10
                    END
        RETURN @Result
END

My question is, calling an UDF from an SP have any performance issues? Is there a better way to achieve the same functionality?

Thanks for your advise...

like image 311
roncansan Avatar asked May 03 '26 21:05

roncansan


1 Answers

Yes this is a bad use of scalar UDFs. This should perform much better.

SELECT 
      id,
      name,
      [begin],
      [end]
FROM 
      orders o
WHERE EXISTS(
            SELECT  *   
            FROM access         
            WHERE orderId = o.id AND [user] = @user AND role >= 1
           )

Some discussion on Scalar UDFs and performance here

like image 110
Martin Smith Avatar answered May 05 '26 09:05

Martin Smith