I've got a SQL request that takes very long time to execute. So I want to make it better but don't known how to do it. Here is an example: My request:
SELECT * from T1
Inner join T2 on T1.a = T2.b
Inner join T3 on T2.c = T3.d
WHERE 1=1
AND T2.e = 'a certain value' --I call i the Clause1
and dbo.MyUDF(T1.id) = 1 --I call i the Clause2
It seems that the problem comes from the UDF call. Running the request without Clause1 and Clause2 will give me 2500rows taking 7 sec.
Running the request without Clause2 will give me 16 rows taking 9 sec.
running the request with all 2 clauses will give me 15 rows taking 1:45 min.
but calling MyUdf 16X in a cursor will take 9Seconds.
declare curs cursor
for SELECT T1.id from T1
Inner join T2 on T1.a = T2.b
Inner join T3 on T2.c = T3.d
WHERE 1=1
AND T2.e = 'a certain value'
open curs
fetch next from curs into @fid
while(@@FETCH_STATUS = 0)
BEGIN
select dbo.MyUdf(@fid)
fetch next from curs into @fid
END
close curs
deallocate curs
So it seems that de SQL Engine test de all 2500 rows with the UDF and the runs Clause1. And I would like that it does the other so the UDF will be called only on 16 rows.
any idea ?
--Edit-- Having a look at the execution plan, It tells that my UDF will not use very mutch. So I think it always take it first. So I need to tell sql server that this part of the request is the worst and that it must take it at last steap. Do you know how to do that ?