Quantcast
Viewing all articles
Browse latest Browse all 207

How can I optimize a recursive CTE inside a IVTF?

I have a recursive CTE inside a inline table-valued function. The ITVF is returning a list of IDs containing a long sequence of ancestors for a person, it usually loops back about 12 to 18 times before getting to the end. It's quite fast but there's an error in the estimations that stacks when used in on many people, so it becomes extremely slow.

The CTE looks like this

WITH ancestors AS (  SELECT    IndID,    AncestorID  FROM    dbo.persons  UNION ALL  SELECT     IndID,    AncestorID  FROM    ancestors a    INNER JOIN dbo.persons p ON p.IndID = a.AncestorID)SELECT IndID, AncestorID FROM ancestors

I have a dozen million rows so it's quite a large table. When I ask for one IndID, the execution plan says that it estimated 7 rows but got 1300 actual rows. For a single request it's acceptable (runs in less than a second) but if I join it in an other request so it gets called, let's say 100 times, the speed drops to a crawl since the estimation is getting worse and worse.

Just to be clear, the estimation error is present even out of the IVTF. I only specified it to be clear that I can't just use a temporary table. It needs to stay in a IVTF so I can join it in larger, more complex requests and it stays parallelable. What can I do to estimate the rows better?

Update : Paste The Plan

Update 2 : Less simplified


Viewing all articles
Browse latest Browse all 207

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>