SQL Server 2005: Recursive Query (aka Common Table Expression)

SQL recursion for cascading results from the same table.
-- UP THE TREE
DECLARE @Id INT
SET @Id = 1

BEGIN
WITH myTree (Id, ParentId, Field)
AS (
-- anchor member declaration
SELECT Id, ParentId, Field FROM myTable WHERE ParentId = @Id
UNION ALL
-- recursive member declaration
SELECT myTable.Id, myTable.ParentId, myTable.Field FROM myTable INNER JOIN myTree ON myTree.Id = myTable.ParentId
)
SELECT DISTINCT * FROM myTable INNER JOIN myTree ON myTree.Id = myTable.Id
END


-- DOWN THE TREE
BEGIN
WITH myTree (Id, ParentId, Field)
AS (
-- anchor member declaration
SELECT Id, ParentId, Field FROM myTable WHERE Id = @Id
UNION ALL
-- recursive member declarationjavascript:void(0)
SELECT myTable.Id, myTable.ParentId, myTable.Field FROM myTable
INNER JOIN myTree ON myTree.ParentId = myTable.OrgId
)
SELECT DISTINCT * FROM myTable INNER JOIN myTree ON myTree.Id = myTable.Id
END


I can't believe they call recursive queries "common table expressions." Who does that make sense to?

3 comments:

Anonymous said...

Nice post! Thanks. Although isn't it 1) down the tree and 2) up the tree..

Michael said...

Yeah, the First one searches towards the leaves of the tree (returning all children of the given record), commonly known as "down" and the second one searches towards the root (returning parent, grand parent, great grandparent etc of the given record) commonly "up" the tree.



Very handy, thanks a lot!

CyberWolf08 said...

Thanks a lot. Helped me quite a lot because i have been trying to make a query work for more than 2 hours before I found this piece of code