user989988
user989988

Reputation: 3736

Use OPTION (MAXRECURSION 0)

I have the following sql query that is run on a hierarchical data:

WITH DirectReports(RootId, ManagerId, Id, RelativeEmployeeLevel) AS
(
    SELECT Id RootId, ManagerId, Id, 0 AS RelativeEmployeeLevel
    FROM tbl    
    UNION ALL
    SELECT d.RootId, e.ManagerId, e.Id, RelativeEmployeeLevel + 1
    FROM tbl AS e
        INNER JOIN DirectReports AS d
        ON e.ManagerId = d.Id   
), q2 as
(
    SELECT RootId,
           ManagerId,
           Id,           
           RelativeEmployeeLevel,
           max(RelativeEmployeeLevel) over (partition by RootId) - RelativeEmployeeLevel LevelsBelow
    FROM DirectReports  
)

SELECT * FROM q2 where rootid = Id

On running this, I see this error: 'The statement terminated. The maximum recursion 100 has been exhausted before statement completion'

I updated the query to include:

OPTION (MAXRECURSION 0)

WITH DirectReports(RootId, ManagerId, Id, RelativeEmployeeLevel) AS
(
    SELECT Id RootId, ManagerId, Id, 0 AS RelativeEmployeeLevel
    FROM tbl    
    UNION ALL
    SELECT d.RootId, e.ManagerId, e.Id, RelativeEmployeeLevel + 1
    FROM tbl AS e
        INNER JOIN DirectReports AS d
        ON e.ManagerId = d.Id   
), q2 as
(
    SELECT RootId,
           ManagerId,
           Id,           
           RelativeEmployeeLevel,
           max(RelativeEmployeeLevel) over (partition by RootId) - RelativeEmployeeLevel LevelsBelow
    FROM DirectReports  
    OPTION (MAXRECURSION 0)
)

SELECT * FROM q2 where rootid = Id

I see an error: Incorrect syntax near the keyword 'OPTION'

What am I missing?

Upvotes: 0

Views: 669

Answers (1)

dougp
dougp

Reputation: 3089

You're trying to use a recursive CTE to return a top-down view of the organization starting with every employee. I doubt every employee is at the top of the organization. If they were, there would be no reason to do this. My guess is that there is one person at the top.

Try this first without OPTION(MAXRECURSION = 0). I can't imagine you have over 100 layers of management.

WITH DirectReports(RootId, ManagerId, Id, RelativeEmployeeLevel) AS
(
    SELECT Id RootId, ManagerId, Id, 0 AS RelativeEmployeeLevel
    FROM tbl
WHERE EmployeeName = 'Head Honcho'
    UNION ALL
    SELECT d.RootId, e.ManagerId, e.Id, RelativeEmployeeLevel + 1
    FROM tbl AS e
        INNER JOIN DirectReports AS d
        ON e.ManagerId = d.Id   
), q2 as
(
    SELECT RootId,
           ManagerId,
           Id,           
           RelativeEmployeeLevel,
           max(RelativeEmployeeLevel) over (partition by RootId) - RelativeEmployeeLevel LevelsBelow
    FROM DirectReports  
)

SELECT * FROM q2 where rootid = Id

Upvotes: 0

Related Questions