在项目中遇到了一个层级关系,情况如下,要在用户信息表中找到汇报给大区销售经理的员工信息(含汇报给大区销售经理的员工的员工),
1 及:大区销售经理
2级:汇报给大区销售经理的直接汇报对象
3级:汇报给2级的直接对象;
为了以后方便查找此资料,现在我把大区销售经理的id 看成2,T-SQL语句如下:
T-SQL
1 With temp_1 AS(
2 SELECT ee.EmployeeID ,ee.LastName +' '+ee.FirstName as Name FROM Employees ee INNER JOIN Employees tt ON tt.EmployeeID = ee.ReportsTo
3 WHERE tt.EmployeeID = 2
4 ),
5 temp_2 AS(
6 SELECT EmployeeID,Name FROM temp_1
7 UNION
8 SELECT ee.EmployeeID,ee.LastName+' '+ee.FirstName as Name FROM Employees ee INNER JOIN temp_1 tt ON tt.EmployeeID = ee.ReportsTo
9 )
另一种方式是创建一个sql 的function
View Code
1 CREATE FUNCTION dbo.FnGetReports(@EmpolyeeID AS INT)
2 RETURNS @Reports TABLE
3 (
4 EmployeeID INT NOT NULL,
5 ReportToID INT NULL
6 )
7 AS
8 BEGIN
9 DECLARE @Employee INT;
10 INSERT INTO @Reports SELECT EmployeeID,ReportsTo FROM Employees WHERE EmployeeID=@EmpolyeeID;
11 SELECT @Employee=MIN(EmployeeID) FROM Employees WHERE ReportsTo=@EmpolyeeID;
12 WHILE @Employee IS NOT NULL
13 BEGIN
14 INSERT INTO @Reports SELECT * FROM dbo.FnGetReports(@Employee);
15 SELECT @Employee = MIN(EmployeeID)
16 FROM Employees
17 WHERE EmployeeID>@Employee
18 AND ReportsTo=@EmpolyeeID
19 END
20 RETURN
21 END
22 GO
调用方式:
1 DECLARE @EmployeeID INT;
2 SELECT @EmployeeID = 2;
3 SELECT ee.EmployeeID,ee.LastName+' '+ ee.FirstName,tt.LastName+' '+TT.FirstName AS 'ReportTo'
4 FROM Employees AS ee
5 INNER JOIN DBO.FnGetReports(@EmployeeID) AS aa ON ee.EmployeeID = aa.EmployeeID
6 INNER JOIN Employees tt ON tt.EmployeeID = aa.ReportToID
怀揣着一点点梦想的年轻人
相信技术和创新的力量
喜欢快速反应的工作节奏
相信技术和创新的力量
喜欢快速反应的工作节奏