mameesh
mameesh

Reputation: 3761

Does calling a scalar function in a select statement multiple times run the function multiple times, and how to get around that if so

If I have a select statement with a scalar function in it used in various calculations, does that scalar function get called multiple times? If it does, is there a way to optimize this so it only calls the funciton once per select, as in my real query it will be called thousands of times, X 6 times per select.

For example:

SELECT 
[dbo].[fn_Days](@Account) + u.[DayRate],
[dbo].[fn_Days](@Account) / u.[WorkDays]
FROM [dbo].[tblUnit] u

All fn_days does is return an int of days worked.

Upvotes: 8

Views: 8684

Answers (2)

Mikael Eriksson
Mikael Eriksson

Reputation: 138990

Functions are deterministic which means that it will always return the same value for a given parameter. You are using a variable as the parameter so you can call the function once before executing the query and use the result in the query instead of calling the function.

DECLARE @Days int
SET @Days = [dbo].[fn_Days](@Account)

SELECT 
  @Days + u.[DayRate],
  @Days / u.[WorkDays]
FROM [dbo].[tblUnit] u  

Upvotes: 3

Steve Stedman
Steve Stedman

Reputation: 2672

Yes the scalar gets called multiple times the way that you have coded it. One way to make it work would be to wrap it into a subquery like this:

SELECT t.[days] + t.[DayRate],
       t.[days] / t.[WorkDays]
FROM (
     SELECT 
     [dbo].[fn_Days](@Account) as days,
     u.[DayRate],
     u.[WorkDays]
     FROM [dbo].[tblUnit] u) as t

This way fn_Days only gets called once per row, rather than twice, or six times like you mentioned.

Hope this helps.

Upvotes: 12

Related Questions