2

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

我正在尝试将参数传递给 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
')
4

1 回答 1

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)
于 2012-08-29T19:01:43.773 回答