I have a query where I use an scalar function. The value of the only function parameter is taken from a field in my query (like this):
SELECT
fn_MyFunc(MyField)
FROM MyTable
If there are several thousand rows in this table, and there are only a few distinct values in MyField, is the optimizer smart enough to know that it has seen that value before or will it still execute the function over and over again?
User defined function stores the execution plan only. No optimiser in existence would be able to cache this useful information. The scalar udf is a black box. the optimizer will not manually memoize UDFs for you.
Solution to increase performance if function is Deterministic means that the same inputs return the same output independent of time and database:
Create a table for all possible results of this UDF and JOIN the table this with the query. It will give best performance/