sql - Closure Table INSERT 语句包括水平/距离列

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

我指的是 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 

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

最佳答案

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

关于sql - Closure Table INSERT 语句包括水平/距离列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18622698/

相关文章:

sql - 数量未知的 PostgreSQL 一对多

javascript - 多个textboxex并在angularjs中插入查询

sql-server - 如何在SQL Server 表的所有列中选择具有空值的行?

sql - 有什么方法可以按文本列分组吗?

c# - 如何查询查询结果集中所有字段的内容?

sql - 我如何使用 LIKE 运算符在 SQL Server 中进行匹配?

SQL 仅在 if 语句内抛出

sql - 无法使用 SQL 创建表

sql - 表规范化(将逗号分隔的字段解析为单独的记录)

mysql - SQL:显示 "running"事件