SQL: How to get depth from a recursive cte

By | January 19, 2017

If you need to know what level deep you are when recursing through a series of parent child relationships, there is a pretty easy way.

DECLARE @Folders TABLE ( ID INT NOT NULL, FolderTypeLID INT NOT NULL, Depth INT NOT NULL,SortOrder INT NOT NULL );
WITH cteFolder( FolderID,Depth )
AS
(
SELECT @topFolderID,Depth = 0
UNION ALL
SELECT f.ID, Depth +1
FROM Folder f
JOIN cteFolder cte
ON f.ParentID = cte.FolderID
)

 

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *