Search code examples
sqlsql-servert-sqlstored-procedurestransitive-closure-table

Closure Table INSERT statement including the level/distance column


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?


Solution

  • 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