在现有父子关系表中填充hierarchyid列?

时间:2011-03-11 17:12:40

标签: sql-server sql-server-2008 recursive-query hierarchyid

我搜索一种填充现有父子表的方法:

Tabelle: Categories
-------------------
Columns: CategoryID
         ParentID

我将我的sql server升级到2008 R2。现在我添加了新的hierarchyid-datatype来优化性能。

所以我想编写一个sql-trigger重新组织hierarchyid-column,当​​插入/更新将调用...但我不是一个SQL专家,所以我希望有人可以帮助我。

测试查询:(我需要在每次递归调用时附加字符串)

;WITH CTE (CategoryID, ParentID, HierarchyString) AS (
    SELECT CategoryID, ParentID, HierarchyString = CAST(ParentID AS VARCHAR(8000)) + '/' + CAST(CategoryID AS VARCHAR(8000))
    FROM Categories
    UNION ALL
    SELECT r.CategoryID, r.ParentID, HierarchyString = CAST(p.CategoryID AS VARCHAR(8000)) + '/' + CAST(r.ParentID AS VARCHAR(8000))
    FROM Categories r 
    INNER JOIN CTE p ON r.CategoryID = p.ParentID
)

SELECT * FROM CTE;

1 个答案:

答案 0 :(得分:2)

我测试了很多查询,现在以下查询有效,但它绝对不干净/优化......也许有人可以改进查询。

;WITH CTE (CategoryID, ParentID, Hierarchy) AS (
    SELECT CategoryID, ParentID, Hierarchy
    FROM Categories
    UNION ALL
    SELECT  p.CategoryID, r.ParentID, hierarchyid::Parse(REPLACE((r.Hierarchy.ToString() + p.Hierarchy.ToString()), '//', '/'))
    FROM Categories r
    INNER JOIN CTE p ON r.CategoryID = p.ParentID
)

SELECT CTE.CategoryID, R.ParentID, CTE.Hierarchy.ToString()
FROM CTE
INNER JOIN Categories AS R ON CTE.CategoryID = R.CategoryID
WHERE CTE.Hierarchy.ToString() LIKE '%/' + CAST(CTE.ParentID AS VARCHAR) + '/' + CAST(CTE.CategoryID AS VARCHAR) + '/%' OR CTE.ParentID = 0