使用openquery连接到Active Directory

时间:2012-08-29 18:52:48

标签: sql-server active-directory

我有以下代码连接到我的活动目录,然后拉出某个组中的用户。由于代码在下面它工作正常,但我必须硬编码我想要查看的部门。

我正在尝试将参数传递给openqueries第二个参数(第二个代码),但我一直收到错误,我知道我的引号有问题,非常感谢任何帮助,谢谢,

select *
from openquery(ADSI, '

select
givenName, 
sn, 
sAMAccountName, 
displayName,
mail, 
telephoneNumber, 
mobile, 
physicalDeliveryOfficeName, 
department, 
division


from ''LDAP://DC=directorysync,DC=cfc, DC=com'' 
where objectCategory = ''Person'' 
and objectClass = ''user''
and department = ''Production''
AND displayname <> ''0_UW_Template_Remote''
ORDER BY displayName
')



select *
from openquery(ADSI, '

select
givenName, 
sn, 
sAMAccountName, 
displayName,
mail, 
telephoneNumber, 
mobile, 
physicalDeliveryOfficeName, 
department, 
division


from ''LDAP://DC=directorysync,DC=cfc, DC=com'' 
where objectCategory = ''Person'' 
and objectClass = ''user''
and department = '''+@Department+'''
AND displayname <> ''0_UW_Template_Remote''
ORDER BY displayName
')

1 个答案:

答案 0 :(得分:3)

您无法在openquery调用中构造查询,您需要在变量中构建查询然后执行它。

declare @qry varchar(8000)
set @qry = 'select *
from openquery(ADSI, ''
    select
    givenName, 
    sn, 
    sAMAccountName, 
    displayName,
    mail, 
    telephoneNumber, 
    mobile, 
    physicalDeliveryOfficeName, 
    department, 
    division


    from ''''LDAP://DC=directorysync,DC=cfc, DC=com'''' 
    where objectCategory = ''''Person'''' 
    and objectClass = ''''user''''
    and department = '''''+@Department+'''''
    AND displayname <> ''''0_UW_Template_Remote''''
    ORDER BY displayName
'')'

exec(@qry)