Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / SQL

SQL Server Recursive Fetch From Self Referencing Table

5.00/5 (2 votes)
19 Nov 2009CPOL 13.9K  
CREATE PROC GetChildNodes (@ID uniqueidentifier)ASBEGINWITH PermissionList (PermissionID, PermissionName, Level)AS(SELECT ap.PermissionID, ap.PermissionName, 0 AS LevelFROM Permission AS apWHERE PermissionID = @IDUNION ALLSELECT ap.PermissionID, ap.PermissionName, Level + 1FROM
CREATE PROC GetChildNodes (@ID uniqueidentifier)
AS
BEGIN
WITH PermissionList (PermissionID, PermissionName, Level)
AS
(
SELECT ap.PermissionID, ap.PermissionName, 0 AS Level
FROM Permission AS ap
WHERE PermissionID = @ID
UNION ALL
SELECT ap.PermissionID, ap.PermissionName, Level + 1
FROM Permission AS ap
INNER JOIN PermissionList AS pl
ON ap.ParentPermissionID = pl.PermissionID
) 

SELECT PermissionID, PermissionName, Level
FROM PermissionList 

END

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)