Created
January 27, 2015 20:22
-
-
Save CodyEngel/fb669edffa19403e30ad to your computer and use it in GitHub Desktop.
Find Parent Nodes Of Child
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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