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?