【问题标题】:Closure Table INSERT statement including the level/distance column包含级别/距离列的闭包表 INSERT 语句
【发布时间】:2013-09-04 19:56:35
【问题描述】:

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

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 

我不确定我该怎么做。有什么想法吗?

【问题讨论】:

    标签: sql sql-server tsql stored-procedures transitive-closure-table


    【解决方案1】:

    您知道,对于 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
    

    【讨论】:

    • 说真的?!就这么简单?我现在感觉很愚蠢...感谢您的帮助,非常感谢:)
    • 我在工作中使用这个模型来做树,所以对我来说很熟悉,有时简单的事情一开始很难理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多