Hello,
I've cretaed a TVF which returns a table with parent-records from a recursive CTE here. That works excellent and the result is available directly. Now i wanted to get the child-records(they have the same FK as the current record's PK). The problem is that it takes 1:10 minutes to get 22 child-records for a given id. Why is this so slow compared to the opposite TVF which looks for parent-records?
This is the ITVF:
CREATE FUNCTION [dbo].[_nextClaimsByIdData] (
@idData INT
)
RETURNS TABLE AS
RETURN(
WITH NextClaims
AS(
SELECT 1 AS relationLevel, child.*
FROM tabData child
WHERE child.fiData = @idData
UNION ALL
SELECT relationLevel+1, parent.*
FROM NextClaims nextOne
INNER JOIN tabData parent ON parent.fiData = nextOne.idData
)
SELECT TOP 100 PERCENT * FROM NextClaims order by relationLevel
)
This is the relationship:
And the following the (correct) result for an exemplary query:
select relationLevel,idData,fiData from dbo._nextClaimsByIdData(30755592);
rl idData fiData
1 30073279 30755592
2 30765260 30073279
3 31942491 30765260
4 30895945 31942491
5 48045119 30895945
6 48342321 48045119
7 48342320 48342321
8 48308966 48342320
9 48308965 48308966
10 47044261 48308965
11 47044260 47044261
12 47253273 47044260
13 47253272 47253273
14 47279292 47253272
15 47279293 47279292
15 47494589 47279292
16 47494588 47494589
17 46051999 47494588
18 46373053 46051999
19 46083426 46373053
20 46099567 46083426
21 46600314 46099567
22 46595167 46600314
It it possible that the cause for the performace lost is that in my first TVF(linked above) i'm looking for primary keys and in this TVF i am searching for (self referencing) foreign keys? If yes, how can i optimize my table-schema to accelerate the query?
UPDATE: I've found out that the cause for this performance issue was that there was no Index on fiData(the foreignkey-column on the table's primary key). After creating and reorganizing, the result came immediately.
Thank you.