简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM