Assuming you are using a fairly modern version of SQL Server, you can use a hierarchyid data type with a little elbow lubrication. First, setting:
alter table [dbo].[yourTable] add [path] hierarchyid null;
Then we write a new column:
with cte as ( select *, cast(concat('/', ID, '/') as varchar(max)) as [path] from [dbo].[yourTable] where [ParentID] is null union all select child.*, cast(concat(parent.path, child.ID, '/') as varchar(max)) as [path] from [dbo].[yourTable] as child join cte as parent on child.ParentID = parent.ID ) update t set path = c.path from [dbo].[yourTable] as t join cte as c on t.ID = c.ID;
This is just a standard swamp table recursive expression with one computed column representing a hierarchy. This is the hard part. Your procedure may now look something like this:
create procedure dbo.GetPositions ( @id int ) as begin declare @h hierarchyid set @h = (select Path from [dbo].[yourTable] where ID = @id); select ID, ParentID, Name from [dbo].[yourTable] where Path.IsDescendentOf(@h) = 1; end
So, to complete, all you do with the hierarchy is to save the line for a given row so that you donβt have to calculate it on the fly at a specific time.
source share