CROSS APPLY with table valued function restriction performance

こ雲淡風輕ζ 提交于 2019-12-05 02:13:07

you can divide this query into 2 parts use either table variable or temp table

SELECT lor.*,at.* into #tempresult
FROM (
    SELECT lor.*
    FROM LOT_OF_ROWS_TABLE lor
    WHERE ...
) lor
INNER JOIN ANOTHER_TABLE AS at ON lor.ID = at.ID 
WHERE ...

now do the time consuming part which is table valued function right

SELECT  * FROM #tempresult
CROSS APPLY dbo.HeavyTableValuedFunction(#tempresult.ID) AS htvf

I believe this is what you are looking for.

Plan Forcing Scenario: Create a Plan Guide to Force a Plan Obtained from a Rewritten Query

Basically it describes re-writing the query to get a generated plan using the correct order of joins. Then saving off that plan and forcing your existing query (that does not get changed) to use the plan you saved off.

The BOL link I put in even gives a specific example of re-writing the query putting the joins in a different order and using a FORCE ORDER hint. Then using sp_create_plan_guild to take the plan from the re-written query and use it on the original query.

Fandango68

YES and NO... it's hard to interprit what you're trying to achieve without sample data IN and result OUT, to compare outcomes.

I'd like to know:

Is there any setting or hint or something that forces select to call function only for finally restricted rows?

So I'll answer your question above (3 years later!!) directly, with a direct statement:

You need to learn about CTE and the difference between CROSS APPLY compared to INNER JOIN and why using CROSS APPLY in your case is necessary. You "could" take the code in your function and apply it into a single SQL statement using CTE.

ie:

Read this and this.

Essentially, something like this...

WITH    t2o AS
        (
        SELECT  t2.*, ROW_NUMBER() OVER (PARTITION BY t1_id ORDER BY rank) AS rn
        FROM    t2
        )
SELECT  t1.*, t2o.*
FROM    t1
INNER JOIN
        t2o
ON      t2o.t1_id = t1.id
        AND t2o.rn <= 3

Apply your query to extrapolate the date you want ONCE, and using CTE, then apply your second SQL using the CROSS APPLY.

You have no choice. You cannot do what you're trying to do in ONE SQL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!