Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying Active Directory from SQL Server 2005

How can I query Active Directory from SQL Server 2005?

like image 608
ecleel Avatar asked Aug 09 '09 09:08

ecleel


2 Answers

Pretty general question but here are some pointers.

You need a linked server creating on the SQL Server that points to ADSI (Active Directory Service Interface) something like this will do it.

EXEC sp_addlinkedserver 'ADSI', 'Active Directory Services 2.5', 'ADSDSOObject', 'adsdatasource'

Then you can use the following sort of query.


SELECT *
FROM OPENQUERY(ADSI, 'SELECT sAMAccountName
FROM ''LDAP://DC=MyDC,DC=com,DC=uk''
WHERE objectCategory = ''Person''
AND objectClass = ''user'')

You'll need to set the LDAP:// line appropriately (ask your AD admin for the details) and be aware that distributed adhoc queries using OpenQuery are disabled by default in SQL Server. Once you have the above though it should be pretty easy to google for any particular variations.

like image 167
Steve Homer Avatar answered Sep 19 '22 18:09

Steve Homer


Yes.

Linked server:

EXEC master.dbo.sp_addlinkedserver
    @server = N'ADSI', 
    @srvproduct=N'Active Directory Services',
    @provider=N'ADsDSOObject', 
    @datasrc=N'Servername.domain.com'

Query:

select * from openquery
(
ADSI,'SELECT name 
FROM ''LDAP://Servername.domain.com''
WHERE objectCategory = ''Person'' AND objectClass = ''user''
')

There are lots of examples if you search linked server and LDPA on Google. I say this because LDAP can be quite complicated to work with.

like image 24
gbn Avatar answered Sep 19 '22 18:09

gbn