Creating a Linked Server to the Active Directory
Top
Microsoft Developers Network posts the article MSDN Library: OLE DB Provider for Microsoft Directory Services on querying an AD, which is a good place to start. For some strange reason I did not immediately recognize the reference to adsdatasource, when using the sp_addlinkedserver stored procedure, as a placeholder for the name of the domain when targeting an Active Directory source. There are actually several sources which are applicable here. I would assume that any LDAP data source is valid, including Exchange Server. As a newbie to using SQL Server to talk to an Active Directory, I had a particularly difficult time following the Microsoft Documentation.
When talking to an Active Directory programmatically, it is often ideal not to have to hard code information about the Forest or Trees in the domain structure. In a perfect world, it is helpful to learn what specific domains you can talk to by first asking a general question.
The first line of T-SQL code creates a linked server connection in SQL Server using ADsDSOObject to talk to the RootDSE the root of the AD forest. Notice that argument, adsdatasource, for the stored procedure sp_addlinkedserver, has been replaced with RootDSE, this is something which did not register in my head for some time, and judging from other online posts on this issues, is a common problem. By using RootDSE as the data source, an LDAP query can be built to return data about the domain structure itself. This is particularly useful when the structure changes over time, as applications now have the ability to be aware of the dynamic structure without recompilation by changing hard-coded values.
Exec sp_addlinkedserver 'ADRoot', 'Active Directory Services 2.5',
'ADsDSOObject', 'RootDSE'
Also note, the name of the linked server is ADRoot and not ADSI as is noted in MSDN documentation. You are free to name this anything you like, within the limits of SQL Server and the sp_addlinkedserver stored procedure call. Also note that you can drop a linked server by calling the next line of code.
exec sp_dropserver 'ADRoot'
If you know the name of the domain you wish to query against, often you can simply use that as the adsdatasource data argument.
To create a link to a specific domain, WestDom in these examples, you can execute a sp_addlinkedserver call like the following, which creates a link with the name ADWest with which we now can execute LDAP commands against.
Exec sp_addlinkedserver 'ADWest', 'AD Services for Big Corp Domain',
'ADsDSOObject', 'WestDom'
in : http://www.nerva.com/Computing/Cod [...] xample.htm
