1

I've a question regarding making a function call in WHERE condition of a SELECT statement in my stored procedure. Here is my sample query that mimics my original. I've 3 million records in the production database for primary table CDP. My concern is if there would be any performance impact of using the function testFunction(@UserId) in my WHERE clause.

SELECT C.AwardId, C.ProgramName, Count(ClientId) as Intakes FROM CDP C 
     LEFT JOIN UserRoleEntity URE ON C.AwardId = URE.EntityId 
     LEFT JOIN UserRole UR ON URE.UserRoleId = UR.Id AND UR.CDPUserId = @UserId
WHERE (1=1) -- here I've other filtering criteria for the results
 AND (   testFunction(@UserId) = 0
      OR (UR.ID IS NOT NULL AND UR.CDPUserId = @UserId))
GROUP BY C.AwardId, C.ProgramName

My question is - Does the function get called for EVERY record in the result set? Since there are 3 million records in CDP table, does the function get called 3 million times and impact the performace?

My assumption is that - the function in WHERE clause would be called ONLY ONCE on the final result set, to filter the results.

Will it be ONCE or 3 million times is my question. BTW - my function contains a simple select statement, with inner joins to 2 tables, and returns a numeric value.

1 Answer 1

1

Instead you can do this. Assign the function result to a variable and use it in where clause

declare @check int,
select @check = dbo.testFunction(@UserId)

SELECT C.AwardId, C.ProgramName, Count(ClientId) as Intakes FROM CDP C 
     LEFT JOIN UserRoleEntity URE ON C.AwardId = URE.EntityId 
     LEFT JOIN UserRole UR ON URE.UserRoleId = UR.Id AND UR.CDPUserId = @UserId
WHERE (1=1) -- here I've other filtering criteria for the results
 AND (   @check = 0
      OR (UR.ID IS NOT NULL AND UR.CDPUserId = @UserId))
GROUP BY C.AwardId, C.ProgramName
Sign up to request clarification or add additional context in comments.

2 Comments

Good workaround. Yet, I would first determine if you need it by looking at the query plan.
Awesome! That totally works.. I don't know why I haven't thought about it. Thank you so much!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.