我要说的是:
CREATE TABLE Employees
(
EmployeeId int PRIMARY KEY NOT NULL,
ParentEmployeId int REFERENCES Employees(EmployeeId) NULL,
Name varChar(255)
)
所有记录都有一个主要识别资料,记录能够把另一个记录作为父母。 (My actual schema isn t about Workers, this is only an brief edition for example so if You ve got a better way of Hand original information it not germane to this dialogue.)
插入以下记录:
INSERT INTO Employees VALUES (1, NULL, Company President 1 )
INSERT INTO Employees VALUES (2, NULL, Company President 2 )
INSERT INTO Employees VALUES (3, 1, Company President 1 - VP )
INSERT INTO Employees VALUES (4, 2, Company President 2 - VP )
INSERT INTO Employees VALUES (5, 3, Company President 1 - VP - Secretary )
INSERT INTO Employees VALUES (6, 4, Company President 2 - VP - Secretary )
INSERT INTO Employees VALUES (7, 5, Company President 1 - VP - Secretary - Sandwich Delivery )
这些词语代表:
Company President 1
Company President 1 - VP
Company President 1 - VP - Secretary
Company President 1 - VP - Secretary - Sandwich Delivery
Company President 2
Company President 2 - VP
Company President 2 - VP - Secretary
我试图做的是,所有拥有全国人民力量联盟的员工。 父母就业情况 我想找到链中的最后一人,例如“。 公司总裁 1 - VP - Secretary -WEPliver
和“ Company President 2 - VP - Secretary
下面的CTE向我提供一切东西,包括nes,但我不敢肯定会从这里去。 如果有可能,我想避免治疗。
而且,这是非常重要的,我在其他地方有逻辑,保证雇员只能有1个直属关系。 因此,尽管该表在技术上允许,但<代码>Company President 1将永远不会有两种千兆字节。
WITH EmployeeRec(EmployeeId, ParentEmployeeId, Name, Level) AS
(
SELECT
EmployeeId,
ParentEmployeId,
Name,
1 as [Level]
FROM
Employees
WHERE
ParentEmployeId IS NULL
UNION ALL
SELECT
E.EmployeeId,
E.ParentEmployeId,
E.Name,
R.[Level] + 1
FROM
Employees E
INNER JOIN
EmployeeRec R
ON
E.ParentEmployeId = R.EmployeeId
)
SELECT * FROM EmployeeRec