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

sql, sql-server, t-sql

Solution

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.

Problem

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.

Original source