Hvis alt du vil gøre med dit niveaufelt er at begrænse antallet af rekursioner, bør du være i stand til at bruge en MAXRECURSION
forespørgselstip
, noget som dette:
WITH Department_CTE AS
(
SELECT
DepartmentGroupKey,
ParentDepartmentGroupKey,
DepartmentGroupName
FROM dimDepartmentGroup
WHERE DepartmentGroupKey = 2
UNION ALL
SELECT
Child.DepartmentGroupKey,
Child.ParentDepartmentGroupKey,
Child.DepartmentGroupName
FROM Department_CTE AS Parent
JOIN DimDepartmentGroup AS Child
ON Parent.ParentDepartmentGroupKey = Child.DepartmentGroupKey
)
SELECT * FROM Department_CTE
OPTION (MAXRECURSION 2)
Rediger:
Som svar på spørgsmålet i kommentarerne, nej, du kan ikke undertrykke den fejl, du får, når du gentager flere gange, end din MAXRECURSION-indstilling tillader. Hvis jeg forstår dig rigtigt, kan du gøre sådan noget:
WITH CTE AS
(
-- Start CTE off by selecting the task that was provided to stored procedure.
SELECT Id, 0 as [Level]
FROM [dbo].[TestTable]
WHERE [Id] = 1
-- Recursively add tasks that are children of parent tasks that have already been found in previous iterations.
UNION ALL
SELECT t.Id, [Level] + 1
FROM [dbo].[TestTable] as t
INNER JOIN CTE as tcte
ON t.[ParentId] = tcte.[Id]
WHERE [Level] < 2
),
CTE2 AS
(
SELECT TestTable.*
FROM CTE
INNER JOIN TestTable ON CTE.Id = TestTable.Id
)
SELECT * FROM CTE2;
Dette bør være lige så generisk som det, du har ovenfor, forudsat at du ikke planlægger at ændre de hierarkiske eller primære nøglefelter.