使用CTE Sql Server的父子关系

时间:2014-05-20 16:17:17

标签: sql-server sql-server-2008

我需要创建一个CTE脚本,以便能够选择一个特定员工下的员工,并且能够将父项包括在列表中。

例如我有员工123在他下面有三个雇员,111,222和333,我有一个已经用层次结构创建的三个视图,用户点击123并且应该能够看到111,222和333的信息,我也想包括123的信息。

我应该可以从任何节点开始获取此信息,我的问题是也包括起始节点。

以下是代码:

declare @Personnel AS TABLE
(
   child_id INT NOT NULL PRIMARY KEY,
   parent_id INT 
);

INSERT INTO @Personnel(child_id, parent_id)
   SELECT 111, 123 UNION ALL
   SELECT 222, 123 UNION ALL
   SELECT 333, 123

;WITH ChildsCTE(child_id, parent_id) AS
   (
      SELECT child_id, parent_id
        FROM @Personnel
       WHERE parent_id = 123

       UNION ALL

      SELECT Curr.child_id, Curr.parent_id
        FROM ChildsCTE AS Prev
             INNER JOIN
             @Personnel AS Curr
             ON Curr.parent_id = Prev.child_id
   )
   SELECT C.child_id, C.parent_id
     FROM ChildsCTE AS C

我希望能够检索:

child_id    parent_id
111         123
222         123
333         123

以某种方式加上父母:

child_id    parent_id
111         123
222         123
333         123
123             123 (or NULL)

父母不是顶级员工,可以是任何一个,当然也可以是顶级员工。

1 个答案:

答案 0 :(得分:0)

您只需从 child_id = 123 开始作为起始节点。请参阅SQL Fiddle here

;WITH ChildsCTE(child_id, parent_id) AS
   (
      SELECT child_id, parent_id
        FROM @Personnel
       WHERE child_id = 123

       UNION ALL

      SELECT Curr.child_id, Curr.parent_id
        FROM ChildsCTE AS Prev
             INNER JOIN
             @Personnel AS Curr
             ON Curr.parent_id = Prev.child_id
   )
   SELECT C.child_id, C.parent_id
     FROM ChildsCTE AS C;

如果parent_id(123)的parent_id也是相同的,那么请使用以下查询。 child_id和parent_id都在连接中使用(SQL Fiddle)。

;WITH ChildsCTE(child_id, parent_id) AS
   (
      SELECT child_id, parent_id
        FROM @Personnel
       WHERE child_id = 123 and parent_id = 123

       UNION ALL

      SELECT Curr.child_id, Curr.parent_id
        FROM ChildsCTE AS Prev
             INNER JOIN
             @Personnel AS Curr
             ON Curr.parent_id = Prev.child_id AND Curr.child_id <> Prev.parent_id
   )
   SELECT C.child_id, C.parent_id
     FROM ChildsCTE AS C;