Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 473
mameesh Avatar asked Apr 11 '12 18:04

mameesh


People also ask

How do you call a scalar value function?

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.

How many scalar functions are there in SQL?

There are two kinds of SQL scalar functions, inlined and compiled.

What is the use of scalar function in SQL?

The Scalar Functions in SQL are used to return a single value from the given input value.

What are the scalar functions?

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.


2 Answers

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.

like image 128
Steve Stedman Avatar answered Sep 20 '22 12:09

Steve Stedman


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  
like image 39
Mikael Eriksson Avatar answered Sep 16 '22 12:09

Mikael Eriksson