Table valued functions can have a non-linear execution time.
Let's consider function equivalent for this query:
SELECT (
SELECT SUM(mi.value)
FROM mytable mi
WHERE mi.id <= mo.id
)
FROM mytable mo
ORDER BY
mo.value
This query (that calculates the running SUM
) is fast at the beginning and slow at the end, since on each row from mo
it should sum all the preceding values which requires rewinding the rowsource.
Time taken to calculate SUM
for each row increases as the row numbers increase.
If you make mytable
large enough (say, 100,000
rows, as in your example) and run this query you will see that it takes considerable time.
However, if you apply TOP 5000
to this query you will see that it completes much faster than 1/20
of the time required for the full table.
Most probably, something similar happens in your case too.
To say something more definitely, I need to see the function definition.
Update:
SQL Server
can push predicates into the function.
For instance, I just created this TVF
:
CREATE FUNCTION fn_test()
RETURNS TABLE
AS
RETURN (
SELECT *
FROM master
);
These queries:
SELECT *
FROM fn_test()
WHERE name = @name
SELECT TOP 1000 *
FROM fn_test()
WHERE name = @name
yield different execution plans (the first one uses clustered scan, the second one uses an index seek with a TOP
)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…