Created
October 11, 2021 15:00
-
-
Save pwelter34/66854631b065d9628faa3e48b567dc3e to your computer and use it in GitHub Desktop.
Select Tree
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
CREATE PROCEDURE [dbo].[ClientHierarchy] | |
@clientId UNIQUEIDENTIFIER | |
AS | |
DECLARE @root UNIQUEIDENTIFIER; | |
-- step 1, find hightest node | |
WITH ParentCTE (Id, ParentClientId) AS | |
( | |
SELECT [Id], [ParentClientId] | |
FROM [dbo].[Client] | |
WHERE Id = @clientId | |
UNION ALL | |
-- Recursive up tree | |
SELECT r.[Id], r.[ParentClientId] | |
FROM [dbo].[Client] r | |
INNER JOIN ParentCTE eh ON r.[Id] = eh.[ParentClientId] | |
) | |
SELECT @root = [Id] | |
FROM ParentCTE | |
WHERE [ParentClientId] IS NULL; | |
-- step 2, select full tree | |
WITH ClientCTE (Id, ParentClientId) AS | |
( | |
SELECT [Id], [ParentClientId] | |
FROM [dbo].[Client] | |
WHERE Id = @root | |
UNION ALL | |
-- Recursive down tree | |
SELECT r.[Id], r.[ParentClientId] | |
FROM [dbo].[Client] r | |
INNER JOIN ClientCTE eh ON r.[ParentClientId] = eh.[Id] | |
) | |
SELECT | |
cte.[Id], | |
cte.[ParentClientId], | |
a.[Name], | |
FROM ClientCTE as cte | |
INNER JOIN [Client] a on cte.[Id] = a.[Id] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment