Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table Valued Function where did my query plan go?

I've just wrapped a complex SQL Statement in a Table-valued function on SQLServer 2000. When looking at the Query Plan for a SELECT * FROM dbo.NewFunc it just gives me a Table Scan of the table I have created.

I'm guessing that this is because table is created in tempdb and I am just selecting from it.

So the query is simply :

SELECT * FROM table in tempdb

My questions are:

Is the UDF using the same plan as the complex SQL statement?

How can I tune indexes for this UDF?

Can I see the true plan?

like image 977
Johnno Nolan Avatar asked Sep 16 '09 11:09

Johnno Nolan


1 Answers

Multi-statement table valued functions (TVF) are black boxes to the optimiser for the outer query. You can only see IO, CPU etc from profiler.

The TVF must run to completion and return all rows before any processing happens. That means a where clause will not be optimised for example.

So if this TVF returns a million rows, it has be sorted first.

SELECT TOP 1 x FROM db.MyTVF ORDER BY x DESC

Single statement/inline TVFs do not suffer because they are expanded like macros and evaluated. The example above would evaluate indexes etc.

Also here too: Does query plan optimizer works well with joined/filtered table-valued functions? and Relative Efficiency of JOIN vs APPLY in Microsoft SQL Server 2008

To answer exactly: no, no, and no

I have very few multi statement TVFs: where I do, I have lots of parameters to filter inside the UDF.

like image 107
gbn Avatar answered Sep 23 '22 06:09

gbn