从AD创建员工和经理列表

时间:2013-11-13 19:45:11

标签: sql-server sql-server-2008 sql-server-2008-r2 recursive-query

我有一张员工及其经理的表格:

-- Show the contents of the table
SELECT * FROM ActiveDirectory.dbo.ADUser

Last        First   ManagerDN
Johnson     Brent   CN=Jones\, Bob,OU=IT
Poleman     Debbie  CN=Jones\, Bob,OU=IT
Kismain     Lenni   CN=Jones\, Bob,OU=IT
Braiswool   Marc    CN=Jones\, Bob,OU=IT
Garpial     Pat     CN=Johnson\, Brent,OU=IT
McKinnis    Laurie  CN=Kismain\, Lenni,OU=IT
Thomason    Maddy   CN=Poleman\, Debbie,OU=IT
Dodgers     Kevin   CN=Thomason\, Maddy,OU=IT

我想创建一份员工,经理和经理的清单。为简单起见,假设可以有3个级别:

LastName    FirstName   ManagerDN3                  ManagerDN2                  ManagerDN1
                                                    CN=Braiswool\, Marc,OU=IT   CN=Jones\, Bob,OU=IT
                        CN=Garpial\, Pat,OU=IT      CN=Johnson\, Brent,OU=IT    CN=Jones\, Bob,OU=IT
                        CN=McKinnis\,Laurie,OU=IT   CN=Kismain\, Lenni,OU=IT    CN=Jones\, Bob,OU=IT
                        CN=Thomason\, Maddy,OU=IT   CN=Poleman\, Debbie,OU=IT   CN=Jones\, Bob,OU=IT
Dodgers     Kevin       CN=Thomason\, Maddy,OU=IT   CN=Poleman\, Debbie,OU=IT   CN=Jones\, Bob,OU=IT

以下是创建和填充表格的代码:

-- Create the ADUser table
CREATE TABLE [dbo].[ADUser](
    [Last] [nvarchar](50) NOT NULL,
    [First] [nvarchar](50) NOT NULL,
    [ManagerDN] [nvarchar](50) NOT NULL
)

-- Populate the ADUser table
INSERT INTO [ActiveDirectory].[dbo].[ADUser]
           ([Last]
           ,[First]
           ,[ManagerDN])

SELECT 'Johnson','Brent','CN=Jones\, Bob,OU=IT'
UNION ALL 
SELECT 'Poleman','Debbie','CN=Jones\, Bob,OU=IT'
UNION ALL 
SELECT 'Kismain','Lenni','CN=Jones\, Bob,OU=IT'
UNION ALL 
SELECT 'Braiswool','Marc','CN=Jones\, Bob,OU=IT'
UNION ALL 
SELECT 'Garpial','Pat','CN=Johnson\, Brent,OU=IT'
UNION ALL 
SELECT 'McKinnis','Laurie','CN=Kismain\, Lenni,OU=IT'
UNION ALL 
SELECT 'Thomason','Maddy','CN=Poleman\, Debbie,OU=IT'
UNION ALL 
SELECT 'Dodgers','Kevin','CN=Thomason\, Maddy,OU=IT'

然后我可以查询每个列:

-- Show the Level2 Managers (ManagerDN2)
SELECT Last, First, ManagerDN FROM dbo.ADUser
WHERE ManagerDN = 'CN=Jones\, Bob,OU=IT'

-- Show the Level3 Managers (ManagerDN3)
SELECT Last, First, ManagerDN FROM dbo.ADUser
WHERE ManagerDN IN 
(   SELECT 'CN=' + Last + '\, ' + First + ',OU=IT'
    FROM dbo.ADUser
    WHERE ManagerDN = 'CN=Jones\, Bob,OU=IT'
)

-- Show the Employees
SELECT Last, First, ManagerDN FROM dbo.ADUser
WHERE ManagerDN IN 
(
    SELECT 'CN=' + Last + '\, ' + First + ',OU=IT'
    FROM dbo.ADUser
    WHERE ManagerDN IN 
    (   SELECT 'CN=' + Last + '\, ' + First + ',OU=IT'
        FROM dbo.ADUser
        WHERE ManagerDN = 'CN=Jones\, Bob,OU=IT'
        )
)

如何有效地创建员工及其经理及其经理的列表

由于

1 个答案:

答案 0 :(得分:0)

为什么每个用户都没有唯一的ID?

然后,您可以使用带有此ID的外键链接到一位经理。

但是如果设置了架构并且无法更改架构,则可以查找recursive CTE