如何使用ADSI OPENQUERY连接表

时间:2015-08-28 07:51:23

标签: sql sql-server tsql active-directory

我在下面有这个交易表Record,我需要从ADSI获取用户的电子邮件地址

ID DisplayName 
1  Surname,User1 [Department]
2  Surname,User2 [Department]

ADSI查询:

DECLARE @sql nvarchar(MAX)    
DECLARE @Mail varchar(255) 


set @sql = 'SELECT TOP 1 @Mail = mail
FROM openquery(ADSI ,''    
SELECT  Name, displayName,givenname,distinguishedName, SAMAccountName ,mail    
FROM ''''LDAP://DC=Domain,DC=org'''' WHERE displayName = '''''+@DisplayName+'''''    
'')'    
--print @sql    
 exec sp_executesql @sql,N'@Mail varchar(255)  OUTPUT',@Mail OUTPUT

SELECT @Mail   

期望的输出:

ID DisplayName                 EmailAdrress         
1  Surname,User1 [Department]  User1.Surname@test.com
2  Surname,User2 [Department]  User2.Surname@test.com

我创建了UDF但是我收到了一个错误,其中动态查询无法在UDF中使用

  

只能在函数内执行函数和一些扩展存储过程。

感谢任何帮助。

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为你不要避免循环/光标:

CREATE TABLE #temp(row_id INT IDENTITY(1,1), Id <type>, DisplayName <type>, EmailAddress <type> NULL);

INSERT INTO #temp(Id, DisplayName)
SELECT Id, DisplayName
FROM Record;

DECLARE @index INT = 1,
        @total INT = (SELECT * FROM #temp),
        @sql   NVARCHAR(MAX),    
        @Mail  VARCHAR(255),
        @DisplayName NVARCHAR(100);

WHILE (@index <= @total)
BEGIN
    SELECT  @DisplayName = DisplayName
    FROM #temp
    WHERE [row_id] = @index;

    SET @sql = 
        N'SELECT TOP 1 @Mail = mail
          FROM openquery(ADSI ,''    
          SELECT  Name, displayName,givenname,distinguishedName, SAMAccountName ,mail    
          FROM ''''LDAP://DC=Domain,DC=org'''' WHERE displayName = ''@DisplayName'' '')';    

    EXEC [dbo].[sp_executesql] 
          @sql
         ,N'@DisplayName NVARCHAR(100),
            @Mail VARCHAR(255)  OUTPUT'
         ,@DisplayName                /* Added explicitly parameters */
         ,@Mail OUTPUT;

   UPDATE #temp
   SET EmailAddress = @Mail
   WHERE row_id = @index;

   SET @index += 1;
END

SELECT 
   Id,
   DisplayName,
   EmailAddress
FROM #temp;

不要连接@sql字符串,如:

'... WHERE displayName = '''''+@DisplayName+'''''  '')'  

/* Use explicit parameter for sp_executesql */
'... WHERE displayName = ''@DisplayName'' '')'