Querying Active Directory from SQL Server 2005

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.

Leave a Comment