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.
How do you call a scalar function? First, specify the name of the function after the CREATE FUNCTION keywords. Second, specify a list of parameters surrounded by parentheses after the function name. Third, specify the data type of the return value in the RETURNS statement.
There are two kinds of SQL scalar functions, inlined and compiled.
The Scalar Functions in SQL are used to return a single value from the given input value.
A scalar function is a function that returns one value per invocation; in most cases, you can think of this as returning one value per row. This contrasts with Aggregate Functions, which return one value per group of rows. Perform bitwise operations on expressions. Manipulate conditional expressions.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With