Closure Table INSERT 语句包括级别/距离列

Kas*_*sem 3 sql t-sql sql-server stored-procedures transitive-closure-table

我指的是Bill Karwin 的演示文稿,以实现一个可以帮助我管理层次结构的闭包表。不幸的是,演示文稿没有展示我如何插入/更新Level幻灯片 67 中提到的列;这将非常有用。我一直在考虑,但我无法想出一些我可以测试的具体内容。这是我到目前为止所得到的:

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 
Run Code Online (Sandbox Code Playgroud)

我不知道我怎么能做到这一点。有任何想法吗?

Rom*_*kar 5

你知道对于 Parent = self 你有 Level = 0 并且当你从祖先复制路径时,你只是将 Level 增加 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
Run Code Online (Sandbox Code Playgroud)