Search code examples
sqlsql-serversql-server-2008clrstoredproceduresql-execution-plan

SQL Server - CLR stored proc in scalar function as filter not weighted properly in query optimizer ==> BAD EXECUTION PLAN


I have a query that looks like the following:

SELECT someString  FROM
(
    SELECT someString FROM someTable
    WHERE someField = 1
) X
WHERE dbo.fnMyClrScalarFunction(X.someString) = 0

The problem is that the query optimizer is moving the UDF inside the subquery, where it is applied before the fairly restrictive 'someField = 1' condition. Unfortunately, the UDF is not exactly speedy, and this results in terrible performance. Is there any way to prevent this (aside from using a temp table) or to establish to sql server that the UDF is expensive?

Thanks in advance


Solution

  • "fairly restrictive 'someField = 1' condition"

    Do you have an index on that column. SQL should only apply the scalar function if it thinks it would be faster to do so. If you have an index where the first column is 'someField', then I would recommend that you make sure the statistics for this table is up to date.