2

我寻找一种方法来填充现有的父子表:

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

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

所以我想写一个sql触发器来重组hierarchyid列,当插入/更新会调用......但我不是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;
4

1 回答 1

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
于 2011-03-11T19:55:14.997 回答