开发者

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]
FR开发者_如何学运维OM 
      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...


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


As always with questions re: performance- profile, profile, profile.

Other than that, the only reason I can see that a UDF would cause any performance problems was if it, itself, was particularly inefficient. It should be no less efficient than calling GetDate() in a Stored Proc.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜