In this sql query now facing the below error
The statement terminated. The maximum recursion 100 has been exhausted before statement completion.
WITH rCTE AS(
SELECT H.Person,
H.AssignedTo,
H.Person AS NextPerson,
H.AssignedTo AS NextAssignedTo,
CONVERT(nvarchar(4000),CONCAT('|',H.AssignedTo,'|')) AS ExpectedResult,
1 AS Level
FROM dbo.tblHierarchy H
UNION ALL
SELECT r.Person,
r.AssignedTo,
H.Person AS NextPerson,
H.AssignedTo AS NextAssignedTo,
CONVERT(nvarchar(4000),CONCAT(r.Expectedresult,H.AssignedTo,'|')),
Level 1
FROM dbo.tblHierarchy H
JOIN rCTE r ON r.NextAssignedTo = H.Person),
RNs AS(
SELECT r.Person,
r.AssignedTo,
r.ExpectedResult,
ROW_NUMBER() OVER (PARTITION BY r.Person ORDER BY r.level DESC) AS RN
FROM rCTE r)
SELECT RN.Person,
RN.AssignedTo,
RN.ExpectedResult
FROM RNs RN
WHERE RN = 1
ORDER BY RN.Person;
Not sure where to add option (maxrecursion 0) in the above query to get rid of this error.
CodePudding user response:
The error caused default recursion was 100, but your query might more than that, you can try to add this hint on the end of a query
The server-wide default is 100. When 0 is specified, no limit is applied. Only one MAXRECURSION value can be specified per statement. For more information
I would set a number for that instead of 0
if you have expected the most recursive deep.
WITH rCTE AS(
SELECT H.Person,
H.AssignedTo,
H.Person AS NextPerson,
H.AssignedTo AS NextAssignedTo,
CONVERT(nvarchar(4000),CONCAT('|',H.AssignedTo,'|')) AS ExpectedResult,
1 AS Level
FROM dbo.tblHierarchy H
UNION ALL
SELECT r.Person,
r.AssignedTo,
H.Person AS NextPerson,
H.AssignedTo AS NextAssignedTo,
CONVERT(nvarchar(4000),CONCAT(r.Expectedresult,H.AssignedTo,'|')),
Level 1
FROM dbo.tblHierarchy H
JOIN rCTE r ON r.NextAssignedTo = H.Person),
RNs AS(
SELECT r.Person,
r.AssignedTo,
r.ExpectedResult,
ROW_NUMBER() OVER (PARTITION BY r.Person ORDER BY r.level DESC) AS RN
FROM rCTE r)
SELECT RN.Person,
RN.AssignedTo,
RN.ExpectedResult
FROM RNs RN
WHERE RN = 1
ORDER BY RN.Person
option (maxrecursion 0);