I have an expensive scalar UDF that I need to include in a select statement and use that value to narrow the results in the where clause. The UDF takes parameters from the current row so I can’t just store it in a var and select from that.
Running the UDF twice per row just feels wrong:
Select someField,
someOtherField,
dbo.MyExpensiveScalarUDF(someField, someOtherField)
from someTable
where dbo.MyExpensiveScalarUDF(someField, someOtherField) in (aHandfulOfValues)
How do I clean this up so that the function only runs once per row?
Just because you happen to mention the function twice doesn’t mean it will be computed twice per row. With luck, the query optimizer will computed it only once per row. Whether it does or not may depend in part on whether the UDF appears to be deterministic or nondeterministic.
Take a look at the estimated execution plan. Maybe you’ll find out you’re worrying about nothing.
If it’s computed twice, you could try this and see if it changes the plan, but it’s still no guarantee: