In the following t-sql statement, how many times will the dbo.FUNC function get called?
SELECT
column1,
column2,
dbo.FUNC(column3) AS column3
FROM table1
WHERE dbo.FUNC(column3) >= 5
ORDER BY dbo.FUNC(column3) DESC
Will it called multiple separate times per row, or does the optimizer recognize that it is being used multiple times in a single statement, and only call it once?
How can I test this? I can’t insert into a table inside of a function, so incrementing a counter wont work…
This isn’t guaranteed.
You would need to check the execution plan to find out. Some examples.
FUNC2is createdWITH SCHEMABINDINGand is treated as deterministic.FUNC1isn’t.Gives Plan
FUNC1is evaluated twice (once in the filter and once in a compute scalar outputting a calculated column used for both the projection and the ordering),FUNC2is only evaluated once.Rewriting as
Changes the plan slightly and both are only evaluated once
Now making a slight alteration to the query
Gives the opposite of the original result in that
FUNC2is evaluated twice butFUNC1only once.