构建查询字符串,以便通过SQL Server查询LDAP

时间:2015-03-31 20:25:28

标签: sql sql-server active-directory ldap

INPUT_STRING NVARCHAR(MAX)
RETURNS NVARCHAR(MAX)
AS 
BEGIN

DECLARE @NewString NVARCHAR(MAX)
DECLARE @SelectClause NVARCHAR(MAX)
SET @INPUT_STRING = @NewString

SET @SelectClause = 'SELECT *  FROM OpenQuery (' + ' 
  ADSI, ' + '
  ''SELECT  samaccountname
  FROM ''LDAP://' +  @NewString  +
  ')'' + '' AS tblADSI'''

 EXEC sp_EXECUTESQL @SelectClause

输入字符串就是这样的

CN=firstName\, Lastname,OU=MyOU,OU=AnotherOU,OU=Accounts,DC=enterprisenet,DC=org

错误信息为读取。

  

Msg 105,Level 15,State 1,Line 8
  字符串后的未闭合引号')' +' AS tblADSI'    EXEC sp_EXECUTESQL @SelectClause

任何帮助都会非常感谢。

1 个答案:

答案 0 :(得分:0)

试试这个......

declare @INPUT_STRING nvarchar(MAX); 
SET @INPUT_STRING = 'CN=firstName\, Lastname,OU=MyOU,OU=AnotherOU,OU=Accounts,DC=enterprisenet,DC=org';

DECLARE @NewString NVARCHAR(MAX)
DECLARE @SelectClause NVARCHAR(MAX)
SET @NewString = @INPUT_STRING 

SET @SelectClause = N'SELECT *  FROM OpenQuery (ADSI,'
                 +  N'  ''SELECT  samaccountname '
                 +  N'  FROM ''''LDAP://' +  @NewString  + N''''' '') AS tblADSI' 

检查

PRINT @SelectClause


SELECT *  
FROM OpenQuery (ADSI,  
               'SELECT  samaccountname   
                FROM ''LDAP://CN=firstName\, Lastname,OU=MyOU,OU=AnotherOU,OU=Accounts,DC=enterprisenet,DC=org'' 
               ') AS tblADSI