MS SQL 2005 Recursive Query Example
Let’s take as an example the following table:
cmsPage
PageId | ParrentPageId |
---|---|
6 | NULL |
44 | 6 |
50 | 44 |
51 | 44 |
52 | 6 |
Let’s find all children of a page with PageId 44 using a common table expression:
WITH PagesList (PageId)
AS
(
-- Anchor member definition
SELECT PageId FROM cmsPage WHERE PageId=44
UNION ALL
-- Recursive member definition
SELECT c.PageId From cmsPage as c
INNER JOIN PagesList as p
ON c.ParrentPageId = p.PageId
)
-- Statement that executes the CTE
SELECT PageId FROM PagesList
GO
Result would be:
PageId |
---|
44 |
50 |
51 |
Posted on March 10, 2008 by Viktar Karpach