Skip to content

Instantly share code, notes, and snippets.

@CodyEngel
Created January 27, 2015 20:22
Show Gist options
  • Save CodyEngel/fb669edffa19403e30ad to your computer and use it in GitHub Desktop.
Save CodyEngel/fb669edffa19403e30ad to your computer and use it in GitHub Desktop.
Find Parent Nodes Of Child
DECLARE @ID int
SET @ID = -- ID of child node
;WITH cte AS(
SELECT ParentId AS pid, 1 AS lvl
FROM Categories
WHERE Id = @ID
UNION ALL
SELECT a.ParentId as pid, lvl+1
FROM Categories a
INNER JOIN cte b ON a.Id = b.pid AND a.Id <> a.ParentId
)
SELECT pid
FROM cte
ORDER BY lvl DESC
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment