1
DECLARE @Categories TABLE (
        CategoryID INT, 
        CategoryName VARCHAR(20),
        ParentID INT )


        INSERT INTO @Categories(CategoryID, CategoryName, ParentID)
            SELECT 1, 'Company', NULL UNION ALL
            SELECT 2, 'Dept A', 1 UNION ALL
            SELECT 3, 'Dept B', 1 UNION ALL
            SELECT 4, 'DA_Sub_1', 2 UNION ALL
            SELECT 5, 'DA_Sub_2', 2 UNION ALL
            SELECT 6, 'DA_Sub_3', 2 UNION ALL
            SELECT 7, 'DA_Sub_4', 2 UNION ALL
            SELECT 8, 'DA1_I', 4 UNION ALL
            SELECT 9, 'DA1_II', 4
        DECLARE @ID int = 4
        DECLARE @Matched int = (SELECT CASE WHEN ParentID = 0 THEN CategoryID ELSE ParentID END FROM @Categories WHERE CategoryID = @ID)

        ;WITH cte AS (
            SELECT CategoryID, CategoryName, ParentID
            FROM @Categories WHERE ParentID IS NULL
            UNION ALL
            SELECT c.CategoryID, c.CategoryName, c.ParentID
            FROM @Categories c
            INNER JOIN cte p ON p.CategoryID = c.ParentID

    )

输出

CID CName           PID
1   Company         NULL
2   Dept A          1
3   Dept B          1
4   DA_Sub_1        2
5   DA_Sub_2        2
6   DA_Sub_3        2
7   DA_Sub_4        2
8   DA1_I           4
9   DA1_II          4

我想这样做,我可以传递一个变量,它会

1) list Self + Parents
2) list Self + Siblings
3) list Self + Children
4) list Parents
5) list Siblings
6) list children
7) list Parents + Self + Siblings.
8) list self + siblings + children
9) list Parents + Self + Siblings + Children (if any).

我怎样才能实现这些目标?(这是我自己的知识,因为我正在尝试学习层次结构在 t-sql 中的工作方式)。

谢谢

4

1 回答 1

1

为了得到孩子:

SELECT * FROM @Categories WHERE ParentId = @Id

要获取条目本身:

SELECT * FROM @Categories WHERE CategoryId = @Id

要获取父级:

SELECT parent.*
  FROM @Categories parent
  JOIN @Categories self
    ON self.ParentId = parent.CategoryId
 WHERE self.CategoryId = @Id

要获得兄弟姐妹:

SELECT siblings.*
  FROM @Categories parent
  JOIN @Categories self
    ON self.ParentId = parent.CategoryId
  JOIN @Categories siblings
    ON siblings.ParentId = parent.CategoryId
 WHERE self.CategoryId = @Id

获得组合结果的最简单方法是UNION ALL像这样使用:

SELECT * FROM @Categories WHERE ParentId = @Id

UNION ALL

SELECT * FROM @Categories WHERE CategoryId = @Id

UNION ALL

SELECT parent.*
  FROM @Categories parent
  JOIN @Categories self
    ON self.ParentId = parent.CategoryId
 WHERE self.CategoryId = @Id

UNION ALL

SELECT siblings.*
  FROM @Categories parent
  JOIN @Categories self
    ON self.ParentId = parent.CategoryId
  JOIN @Categories siblings
    ON siblings.ParentId = parent.CategoryId
 WHERE self.CategoryId = @Id

您还可以添加一个 HIERARCHYID 列: http: //msdn.microsoft.com/en-us/library/bb677290.aspx 这将使查询的资源密集度降低一些,但需要在表中添加一个列。

于 2013-04-20T00:42:05.343 回答