SQL查询/存储过程以获取完整的组织层次结构详细信息

时间:2015-08-15 07:32:19

标签: sql-server-2008 tsql stored-procedures common-table-expression

我尝试并搜索了以下问题陈述的解决方案,但不幸的是我没有得到确切的输出。我需要以下面的格式显示完整的组织层次结构。我尝试使用CTE和UNION ALL,但我仍然无法得到确切的输出。

表格结构:

CREATE TABLE EMPMASTER
(
    EMPID CHAR(10),
    EMPNAME NVARCHAR(50),
    EMPDESIG VARCHAR(20),
    MRGID CHAR(10)
);

输出:

EMPNAME     EMPID   EMP DESIGNATION
------------------------------------
EMP1    00001   CEO
EMP2    00009   MANAGER 1
EMP3    00005   TL1
EMP4    00003   SSD1
EMP5    00006   SD1
EMP6    00008   TL2
EMP7    00020   SSD2
EMP8       25   SD2
EMP9    00030   TL3
EMP10   00017   MANAGER2
EMP11   00029   TL4
EMP12   00045   SSD3
EMP13   00060   SSD4
EMP14   00070   SD3
EMP15   00060   SD4
EMP16   00090   SD5
EMP17   00055   SD6
CONTI…  CONTI…  CONTI…

我尝试过的代码:

WITH HierarchyTree (EMPID, EMPNAME, EMPDESIG, MRGID, Rank)
AS
(
    -- Anchor member definition
    SELECT 
        EMPID, EMPNAME, EMPDESIG, MRGID, 0 AS Rank
    FROM
        EMPMASTER AS e
    WHERE 
        DESIGNATION = 'Admin' AND EMPLOYEE_ID='1'

    UNION ALL

    -- Recursive member definition
    SELECT 
        e.EMPID, e.EMPNAME, e.EMPDESIG, e.MRGID, Rank + 1
    FROM 
        EMPMASTER AS e
    INNER JOIN 
        HierarchyTree AS d ON e.REPORTINGTO = d.EMPLOYEE_ID
)
SELECT 
    EMPID, EMPNAME, DESIGNATION, REPORTINGTO, Rank
FROM 
    HierarchyTree

示例数据

EMPID       EMPNAME     EMPDESIG    MRGID
1            RAM          CEO           0
7326         MOHD RAFI    MANAGER       7454
7454         PMT PHARMA   MANAGER       1
2094         VAC SANJAY   DEVELOPER     14005
602          GS           MANAGER       7454
412          RAJESH       LEAD          602
14005        VAC SM N     LEAD          7326
34395        DEEPAK       LEAD          7326
16430        VIJAY        DEVELOPER     34395

enter image description here

0 个答案:

没有答案