Closure Table INSERT statement including the level/distance column
Asked Answered
B

1

3

I'm referring Bill Karwin's presentation in order to implement a closure table which will help me manage hierarchies. Unfortunately, the presentation does not show how I could insert/update the Level column mentioned on slide 67; this would have been very useful. I've been giving it a thought but I couldn't come up with something concrete that I could test. Here's what I got so far:

create procedure USP_OrganizationUnitHierarchy_AddChild 
    @ParentId UNIQUEIDENTIFIER,
    @NewChildId UNIQUEIDENTIFIER
AS
BEGIN
    INSERT INTO [OrganizationUnitHierarchy]
    (
        [AncestorId],
        [DescendantId],
        [Level]
    )
    SELECT [AncestorId], @NewChildId, (here I need to get the count of ancestors that lead to the currently being selected ancestor through-out the tree)
    FROM [OrganizationUnitHierarchy]
    WHERE [DescendantId] = @ParentId
    UNION ALL SELECT @NewChildId, @NewChildId
END
go 

I am not sure how I could do that. Any ideas?

Behm answered 4/9, 2013 at 19:56 Comment(0)
H
5

You know that for Parent = self you have Level = 0 and when you copying paths from ancestor, you're just increasing Level by 1:

create procedure USP_OrganizationUnitHierarchy_AddChild 
    @ParentId UNIQUEIDENTIFIER,
    @NewChildId UNIQUEIDENTIFIER
AS
BEGIN
    INSERT INTO [OrganizationUnitHierarchy]
    (
        [AncestorId],
        [DescendantId],
        [Level]
    )
    SELECT [AncestorId], @NewChildId, [Level] + 1
    FROM [OrganizationUnitHierarchy]
    WHERE [DescendantId] = @ParentId
    UNION ALL
    SELECT @NewChildId, @NewChildId, 0
END
Honorarium answered 4/9, 2013 at 20:6 Comment(2)
Seriously?! It's that simple? I feel so stupid right now... Thanks for the help, much appreciated :)Behm
I'm using this model for trees at work, so it's familiar to me, sometimes simple things is hard to understand at first.Honorarium

© 2022 - 2024 — McMap. All rights reserved.